2013-05-10 66 views
0

我試圖找到一個tk.Toplevel()窗口的大小,這樣我就可以居中:得到一個Tkinter的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'],這不是窗口的大小,因此它不居中窗口...

回答

3
  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))