为什么这不是窗口的中心?

时间:2015-11-27 00:46:38

标签: python tkinter

我正在使用此代码将我的屏幕置于中心位置,如this帖子和我的question所示,但令我惊讶的是它并没有准确地将窗口置于中心位置。它把它放在右下角而不是中心。为什么是这样?

 top1=Toplevel(root)
 w = top1.winfo_screenwidth()
 h = top1.winfo_screenheight()
 topsize = tuple(int(_) for _ in top1.geometry().split('+')[0].split('x'))
 x = w/2 - topsize[0]/2
 y = h/2 - topsize[1]/2
 top1.geometry("+%d+%d" % (topsize[0]+x, topsize[1]+y))
  

Steven Summers的最终解决方案

import Tkinter as tk


def center_window(win):
    w = win.winfo_screenwidth()
    h = win.winfo_screenheight()
    x = w/2 - win.winfo_width()/1-150
    y = h/2 - win.winfo_height()/1-200
    win.geometry("+%d+%d" % (x, y))

root = tk.Tk()
top1 = tk.Toplevel(root)
top1.title('TopLevel Window 1')
top1.minsize(300, 300)

b = tk.Label(top1, text='Here is a Label')
b.pack()
l = tk.Button(top1, text='Click Me')
l.pack()

top1.after(1, lambda: center_window(top1))

root.mainloop()

2 个答案:

答案 0 :(得分:2)

您需要致电root.after(delay, command)来运行此操作。创建窗口小部件并尝试初始化时,大小为1x1。这就是为什么放置它时你的值不正确的原因。同样如所引用问题的答案中所述,使用.winfo_width() and .winfo_height()而不是通过几何来获取值。

import tkinter as tk


def center_window(win):
    w = win.winfo_screenwidth()
    h = win.winfo_screenheight()
    x = w/2 - win.winfo_width()/2
    y = h/2 - win.winfo_height()/2
    win.geometry("+%d+%d" % (x, y))

root = tk.Tk()
top1 = tk.Toplevel(root)
top1.title('TopLevel Window 1')
top1.minsize(300, 300)

b = tk.Label(top1, text='Here is a Label')

top1.after(1, lambda: center_window(top1))

l = tk.Button(top1, text='Click Me')

b.pack()
l.pack()

root.mainloop()

答案 1 :(得分:0)

我认为应该是

top1.geometry("+%d+%d" % (x, y))