import tkinter as tk
root = tk.Tk()
root.title("window")
yellow_header = tk.Label(root, text = 'Header', bg = 'light yellow')
yellow_header.pack(side = tk.TOP, anchor = tk.N, expand = 1, fill = tk.X)
yellow_header2 = tk.Label(root, text = 'paragraph', bg = 'light yellow')
yellow_header2.pack(side = tk.TOP, anchor = tk.N, expand = 1, fill = tk.X)
root.mainloop()
对于上面的代码,我试图将这两个标签固定在顶部和正下方。虽然第一个标签 (yellow_header) 锚定到顶部,但第二个标签 (yellow_header2) 在展开时会向中心移动。我该如何解决这个问题?
提前谢谢您!
最佳答案
不要使用expand=1
。来自 effbot :
The expand option tells the manager to assign additional space to the widget box. If the parent widget is made larger than necessary to hold all packed widgets, any exceeding space will be distributed among all widgets that have the expand option set to a non-zero value.
使用expand=1
,当您增大窗口时,空间会分布在两个标签之间。因此,即使您只告诉他们在 X 方向上填充它,他们也会在两个方向上获得空间。第二个标签直接放置在第一个标签可用的空间下方,即窗口的一半。
我试图解释并可视化 this answer 中的 expand
和 fill
之间的区别.
附注您也不需要 anchor=tk.N
。当小部件的可用空间和小部件的大小相同时, anchor 选项没有区别。另外,side=tk.TOP
是默认值,因此您也可以决定忽略它,只留下 fill=tk.X
。
关于PYTHON:如何使用 tkinter 将两个标签锚定到顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52756009/