关于python:如何设置窗口的大小?

How to set the size of a window?

本问题已经有最佳答案,请猛点这里访问。

如何调整 root 窗口的大小?

1
2
3
4
5
6
7
8
try:                        # In order to be able to import tkinter for
    import tkinter as tk    # either in python 2 or in python 3
except ImportError:
    import Tkinter as tk


root = tk.Tk()
tk.mainloop()

如何调整 window 的大小?

1
2
3
4
5
6
7
8
9
try:                        # In order to be able to import tkinter for
    import tkinter as tk    # either in python 2 or in python 3
except ImportError:
    import Tkinter as tk


root = tk.Tk()
window = tk.Toplevel(root)
tk.mainloop()

可以使用 geometry 方法设置窗口的大小(无论是 Tk 实例还是 Toplevel 实例):

1
2
# identical to root.geometry('256x512')
root.geometry('{}x{}'.format(256, 512))

或:

1
2
# identical to window.geometry('512x256')
window.geometry('{}x{}'.format(512, 256))

另外使用几何方法也可以确定窗口的左上角:

1
window.geometry('+{}+{}'.format(16, 32))

或者两者兼而有之:

1
2
#identical to window.geometry('512x256+16+32')
window.geometry('{}x{}+{}+{}'.format(512, 256, 16, 32))

更一般地说,可以使用 winfo_toplevel 来轻松地从其子窗口设置窗口的大小:

1
widget.winfo_toplevel().geometry('{}x{}+{}+{}'.format(512, 256, 16, 32))

例子

这是一个通过子部件的引用设置窗口大小和位置坐标的示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
try:                        # In order to be able to import tkinter for
    import tkinter as tk    # either in python 2 or in python 3
except ImportError:
    import Tkinter as tk


def on_button_press(widget):
    width = 512
    height = 256
    x = 16
    y = 32
    widget.winfo_toplevel().geometry('{}x{}+{}+{}'.format(width, height, x, y))


if __name__ == '__main__':
    root = tk.Tk()
    window = tk.Toplevel(root)
    button = tk.Button(window, text="Resize & Place")
    #the line below is related to calling a method when a button is pressed
    button['command'] = lambda w=button: on_button_press(w)
    button.pack()
    tk.mainloop()