gpt4 book ai didi

python - 获取 Tkinter Toplevel 的大小

转载 作者:行者123 更新时间:2023-11-28 22:55:44 26 4
gpt4 key购买 nike

我试图找到 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') 只是 ['1', '1'],它不是窗口的大小,所以它不会使窗口居中...

最佳答案

  1. 调用update()在检索任何几何图形之前(mainloop() 尚未启动)
  2. 您可以使用 winfo_width()winfo_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))

关于python - 获取 Tkinter Toplevel 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16485237/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com