Tkinter - 如何水平居中画布文字?

时间:2015-02-26 22:43:07

标签: 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

我希望infoText中的文本水平居中并垂直偏移约200px。垂直偏移工作正常,但我无法弄清楚如何水平居中文本。

我开始尝试年龄((宽度/ 2) - (str长度/ 2)),但后来意识到每个字母不是1px。而anchor =“center”似乎只将文本的一半放在屏幕的左侧。

我是Python的新手(现在只有几天),所以如果我遗漏了一些明显的东西,那就是原因。

编辑:如果不明显,这个文本会改变,所以我不能只对偏移作出绝对的决定,它必须随着文本的改变

3 个答案:

答案 0 :(得分:4)

我在浏览画布参考后想出来了。

有一种名为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

主要部分在这里:

    textID = mainPanel.create_text(0,0, text=infoText, anchor="nw", fill="yellow")
    xOffset = self.findXCenter(mainPanel, textID)
    mainPanel.move(textID, xOffset, 0)

希望我在寻找这个答案的时间会对以后的人有所帮助。

答案 1 :(得分:0)

您是否尝试过使用justify参数? center通常与非文本对象一起使用。

https://stackoverflow.com/a/15016161/3900967可能会提供一些见解。

答案 2 :(得分:0)

您可以使用.create_text()方法的第一部分设置文本的位置。 见http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/create_text.html

要将此位置视为窗口中心,请使用self.windowWidth / 2作为x cordinate

默认情况下,文本锚定在给定位置的中心。 (.create_text将默认为anchor =“CENTER”)

您还需要删除anchor =“nw”,因为这会使您的文字显示在给定位置的右侧

因此,您的更新代码应为。

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(self.windowWidth/2,200, text=infoText, fill="yellow")
return
相关问题