我正在为一个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
我希望infoText中的文本水平居中并垂直向下偏移约200px。垂直偏移量没问题,但我无法弄清如何使文本水平居中。
一开始我试着用老旧的 ((width / 2) - (str length / 2)) 方法,但后来意识到每个字母的宽度不止1像素。 anchor = "center"似乎只能将一半的文本移到屏幕左侧。
由于我才刚接触Python(才几天),如果我忽略了一些显而易见的东西,请谅解。
注:如未明确指出,这段文本将发生变化,因此我不能仅仅对偏移量做出绝对决策,它必须随着文本的变化而变化。
anchor="nw"
属性,因为默认值是anchor="center"
。使用后者,你只需要传递你想要作为文本中心的坐标,而无需进行任何额外的计算。 - josch