Skip to main content
 首页 » 编程设计

python之Tkinter 按钮距窗口边缘的距离

2025年05月04日14EasonJim

有没有一种方法可以使用 Tkinter 使按钮始终位于距离窗口边缘一定数量的像素处,即使在调整窗口大小时也是如此?我试过使用 anchor ,但这似乎并没有使窗口中的位置移动太多。

请您参考如下方法:

您可以通过从 Frame 开始并将其行和列的权重配置为 1 来将按钮或任何其他小部件锚定到窗口的两侧命令它填充父窗口。

import Tkinter as tk 
import ttk 
 
root = tk.Tk() 
 
frame = ttk.Frame(root) 
frame.pack(fill=tk.BOTH, expand=True) 
frame.columnconfigure(index=0, weight=1) 
frame.columnconfigure(index=2, weight=1) 
frame.rowconfigure(index=0, weight=1) 
frame.rowconfigure(index=2, weight=1) 

然后,对于每个要使用 sticky 将其固定到相应侧的按钮,并使用 padx 或 pady 添加一些按钮和窗口之间的填充(以像素为单位)。

top_padding = 5 
top = ttk.Button(frame, text="Top") 
top.grid(row=0, column=1, sticky=tk.N, pady=(top_padding, 0)) 
 
left_padding = 5 
left = ttk.Button(frame, text="Left") 
left.grid(row=1, column=0, sticky=tk.W, padx=(left_padding, 0)) 
 
right_padding = 5 
right = ttk.Button(frame, text="Right") 
right.grid(row=1, column=2, sticky=tk.E, padx=(0, right_padding)) 
 
bottom_padding = 5 
bottom = ttk.Button(frame, text="Bottom") 
bottom.grid(row=2, column=1, sticky=tk.S, pady=(0, bottom_padding)) 
 
root.mainloop()