使用 pack(pady) 的 Tkinter 小部件没有移动

Tkinter widget using pack(pady) is not moving

我正在尝试制作一个应用程序,但遇到了问题。有一个 Frame:

status_frame = Frame(self.root, height=60, style='status.TFrame') # white one at the top 
status_frame.pack_propagate(0)
status_frame.pack(fill=X)

有一个Label

status_label = Label(status_frame, text='Label', style='status_bold.TLabel')

并用pack()方法放置:

status_label.pack(side=LEFT, padx=5)

padx=5 工作正常:

但是如果我添加 pady=25 它不会移动,它会奇怪地切割:

为什么会这样,我怎样才能向上移动 Label?我需要用 pack() 放置它。完整代码:

from tkinter import *
from tkinter.ttk import *

root = Tk()
root.geometry('400x250')
root.resizable(0, 0)

style = Style()
style.configure('status.TFrame', background='white')
style.configure('status_bold.TLabel', background='white', font=('Arial 9 bold'))
style.configure('status.TLabel', background='while')

status_frame = Frame(root, height=60, style='status.TFrame')
status_frame.pack_propagate(0)
main_frame = Frame(root, height=150)
main_frame.pack_propagate(0)
button_frame = Frame(root, height=40)
button_frame.pack_propagate(0)

status_label = Label(status_frame, text='Label', style='status_bold.TLabel')
left_button = Button(button_frame, text='Left')
right_button = Button(button_frame, text='Right')


status_frame.pack(fill=X)
Separator(root, orient=HORIZONTAL).pack(fill=X)
main_frame.pack(fill=X)
Separator(root, orient=HORIZONTAL).pack(fill=X)
button_frame.pack(fill=X)
status_label.pack(side=LEFT, padx=5, pady=25)
right_button.pack(side=RIGHT, padx=5)
left_button.pack(side=RIGHT)

root.mainloop()

因为您关闭了 status_frame 的几何传播并强制 space 正好是 60 像素高,所以没有足够的空间容纳标签和顶部的 25 像素填充底部。使用该填充,它只为标签留下 10 个像素。 Tkinter 别无选择,只能从标签中删除像素。

如果您尝试使用 pady 将标签文本向下移动,您可以像这样在顶部添加填充:

status_label.pack(side=LEFT, padx=5, pady=(25, 0))

如果您希望在顶部和底部都进行填充,那么您应该而不是关闭几何传播。就我个人而言,我认为关闭传播很少是正确的做法。通过保留传播,框架将增大或缩小,以便它始终适合子部件,这在 99+% 的时间里都是您想要的。