PYTHON:如何使用 tkinter 将两个标签锚定到顶部

标签 python user-interface tkinter

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 中的 expandfill 之间的区别.

附注您也不需要 anchor=tk.N 。当小部件的可用空间和小部件的大小相同时, anchor 选项没有区别。另外,side=tk.TOP 是默认值,因此您也可以决定忽略它,只留下 fill=tk.X

关于PYTHON:如何使用 tkinter 将两个标签锚定到顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52756009/

相关文章:

python - 在 python 中解压缩,交互式与脚本调用

python pandas用数字替换数据框中的字符串

python - 我们如何删除已在 Tkinter Canvas 中创建的形状?

python - 如何避免 tkinter 中的 checkbutton 被覆盖

python - 基于 Web 的自动化 GUI 测试工具

python - 为什么我的 .fetchone 函数返回 "none"?

python - 使 Tkinter 组合框滚动条和箭头按钮更大

python - Pandas读取带有中文文件名的excel

Python 将字典列表写入 csv

适用于大型项目的 Java GUI 架构