5

我正在处理作为配置窗口的 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 中的文本水平居中并垂直向下偏移约 200 像素。垂直偏移效果很好,但我不知道如何将文本水平居中。

我开始尝试古老的 ((width / 2) - (str length / 2)),但后来意识到每个字母都不是 1px。而且 anchor = "center" 似乎只将一半的文本放在屏幕左侧。

我对 Python 很陌生(现在只有几天),所以如果我遗漏了一些明显的东西,这就是原因。

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

4

3 回答 3

10

在浏览了画布参考后,我想通了。

有一种用于画布的方法,称为 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)

希望我寻找这个答案的时间能在以后帮助别人。

于 2015-02-27T04:04:32.623 回答
2

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

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

于 2015-02-26T22:52:20.933 回答
0

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

要使此位置水平居中到窗口,请使用 self.windowWidth / 2 作为 x 坐标

默认情况下,文本锚定在给定位置的中心。(.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
于 2015-10-18T03:33:42.597 回答