lin*_*982 2 python tkinter tkinter-canvas
我正在使用UI类中的一个函数,它是一个配置窗口,它显示程序的徽标,并在底部显示一个更新文本,告诉您它正在加载什么,等等。这是我到目前为止的内容:
self.window = "config"
self.windowWidth = 340
self.windowHeight = 270
infoText = "Configuring Kh..."
self.root = tk.Tk()
self.root.geometry("%dx%d+400+400" % (self.windowWidth, self.windowHeight))
self.root.title("Kh Control v1.1 starting...")
logo = tk.PhotoImage(file="KhLogo.gif")
mainPanel = tk.Canvas(self.root, width=self.windowWidth, height=self.windowHeight)
mainPanel.image = logo
mainPanel.pack()
mainPanel.create_image(0, 0, image=logo, anchor="nw")
mainPanel.create_text(0,200, text=infoText, anchor="nw", fill="yellow")
return
Run Code Online (Sandbox Code Playgroud)
我希望infoText中的文本水平居中并垂直向下偏移200px。垂直偏移效果很好,但我不知道如何水平放置文本居中。
我从尝试使用年龄较大的((width / 2)-(str length / 2))开始,但后来意识到每个字母都不是1px。而anchor =“ center”似乎仅将文本的一半放在屏幕的左侧。
我是Python的新手(仅几天),因此,如果我缺少明显的内容,这就是原因。
编辑:并且如果它不是很明显,则此文本将更改,因此我不能仅对偏移量做出绝对决定,它必须随文本更改
我仔细阅读了画布参考资料后,便找到了答案。
对于名为bbox的画布,有一种方法可以返回一个元组,该元组包含(x1,y1,x2,y2)项目占用的区域。我得到了那些坐标,绘制了一个函数来查找它的px长度,将其除以2,然后从窗口宽度中减去它。然后,我使用canvas.move使用函数返回的数字更改x偏移量。
def findXCenter(self, canvas, item):
coords = canvas.bbox(item)
xOffset = (self.windowWidth / 2) - ((coords[2] - coords[0]) / 2)
return xOffset
Run Code Online (Sandbox Code Playgroud)
主要部分在这里:
textID = mainPanel.create_text(0,0, text=infoText, anchor="nw", fill="yellow")
xOffset = self.findXCenter(mainPanel, textID)
mainPanel.move(textID, xOffset, 0)
Run Code Online (Sandbox Code Playgroud)
希望我在搜索此答案的时间中有所帮助。
| 归档时间: |
|
| 查看次数: |
5125 次 |
| 最近记录: |