我正在尝试找到窗口的大小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))
Run Code Online (Sandbox Code Playgroud)
我怎样才能得到实际尺寸?self.masterSize = self.master.geometry().split('+')[0].split('x')只是['1', '1'],这不是窗口的大小,所以它不会使窗口居中......
mainloop() (尚未开始)winfo_width()andwinfo_height()代替解析geometry()输出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))
Run Code Online (Sandbox Code Playgroud)