2

我正在尝试查找tk.Toplevel()窗口的大小,以便将其居中:

class HelpWindow:
    def __init__(self, master):
        self.width, self.height = screenDim
        self.master = master
        self.helpImage = Image.open("someImage.jpg")
        self.helpPhoto = ImageTk.PhotoImage(self.helpImage)
        self.helpLabel = tk.Label(self.master, image = self.helpPhoto)
        self.helpLabel.grid(row = 1)
        self.masterSize = self.master.geometry().split('+')[0].split('x')
            # this is just ['1', '1']; not the actual size
        self.xSize, self.ySize = (float(self.width) / float(self.masterSize[0])), (float(self.height) / float(self.masterSize[1]))
            # this creates the offset
        self.xPos, self.yPos = int(self.width/2 - (self.width/(self.xSize*2))), int(self.height/2 - (self.height/(self.ySize*2))) # this should center it
        self.master.geometry("+{posX}+{posY}".format(posX = self.xPos, posY = self.yPos))

我怎样才能得到实际尺寸?self.masterSize = self.master.geometry().split('+')[0].split('x')is just ['1', '1'],这不是窗口的大小,因此它不会使窗口居中...

4

2 回答 2

4
  1. 在检索任何几何之前调用 update()mainloop() (尚未开始)
  2. 您可以使用winfo_width()andwinfo_height()而不是解析geometry()输出
  3. 您的代码不考虑外框


def center(win):
    win.update()
    w_req, h_req = win.winfo_width(), win.winfo_height()
    w_form = win.winfo_rootx() - win.winfo_x()
    w = w_req + w_form*2
    h = h_req + (win.winfo_rooty() - win.winfo_y()) + w_form
    x = (win.winfo_screenwidth() // 2) - (w // 2)
    y = (win.winfo_screenheight() // 2) - (h // 2)
    win.geometry('{0}x{1}+{2}+{3}'.format(w_req, h_req, x, y))
于 2013-05-10T16:38:38.367 回答
0
text = Entry(window, font="Helvetica 60 bold")
text.place(x=(window.winfo_screenwidth() // 2), y=0, anchor="center")
于 2018-07-28T01:52:07.533 回答