有没有一种使用Tkinter的方法来具有按钮,以便即使调整了窗口的大小,也始终将它们放置在距窗口边缘一定数量的像素处?我已经尝试过使用锚点,但这似乎并没有在窗口中移动太多。

最佳答案

您可以通过从框架开始并将按钮的行和列配置为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()

07-26 09:35
查看更多