python - Tkinter 网格权重的表现不符合我的预期

标签 python python-3.x tkinter

我希望下面的代码生成的文本区域占据屏幕的一半,因为列的权重相等。

为什么文本区域占据了屏幕的 2/3 左右?如何让文本区域只占据屏幕的一半?

from tkinter import *

root = Tk()
root.wm_state('zoomed')
root.columnconfigure(0, weight=1)
root.columnconfigure(1, weight=1)
root.rowconfigure(0, weight=1)

root.configure(bg='red')

info_frame = Frame(root)
info_frame.grid(row=0, column=1, sticky="nsew")
info_frame.columnconfigure(0, weight=1)
info_frame.rowconfigure(0, weight=1)

user_frame = Frame(root, bg='blue')
user_frame.grid(row=0, column=0, sticky="nsew")
user_frame.columnconfigure(0, weight=1)
user_frame.rowconfigure(0, weight=1)
user_frame.rowconfigure(1, weight=1)

button_frame = Frame(user_frame)
button_frame.grid(row=0, column=0, sticky="nsew")

entry_frame = Frame(user_frame)
entry_frame.grid(row=1, column=0, sticky="nsew")

info_display = Text(info_frame, state=DISABLED)
info_display.grid(row=0, column=0, sticky="nsew")

scrollbar = Scrollbar(info_frame)
scrollbar.grid(row=0, column=1, sticky="nsew")

light_label = Label(entry_frame, text='Light').grid(row=0, column=0)
light_entry = Entry(entry_frame).grid(row=0, column=1)
current_label = Label(entry_frame, text='Current').grid(row=1, column=0)
current_entry = Entry(entry_frame).grid(row=1, column=1)

button1 = Button(button_frame, text='button1').grid(row=0, column=0)
button2 = Button(button_frame, text='button2').grid(row=0, column=1)
button3 = Button(button_frame, text='button3').grid(row=1, column=0)
button4 = Button(button_frame, text='button4').grid(row=1, column=1)


root.mainloop()

最佳答案

权重告诉 tkinter 如何分配额外空间,它不是保证列或行具有相同大小的机制。

假设您在第 0 列中放置了一个 100 像素宽的小部件,在第 1 列中放置了一个 200 像素宽的小部件,并且您为两列赋予了相同的权重。 GUI 自然会尝试宽度为 300 像素,因为这就是您所要求的。

如果您使窗口变大(通过交互式调整大小、使用几何方法或缩放窗口),tkinter 将使用权重来决定如何分配额外的/em> 空格。

例如,如果强制 GUI 宽度为 500 像素,则有 200 个未分配的像素。由于每列具有相同的权重,因此每列将有 100 个像素,使一列为 200 像素,另一列为 300。因此,即使它们具有相同的权重,它们也不会具有相同的大小。

如果您希望列具有相同的宽度,可以使用 uniform 选项使列成为统一组的一部分。在该组中,所有列都将具有相同的宽度。

例如,这将保证每列占据一半的空间(由于只有两列有权重,并且它们的大小相同,根据定义它们必须占据窗口的一半)

root.columnconfigure(0, weight=1, uniform="half")
root.columnconfigure(1, weight=1, uniform="half")

注意:您可以使用任何您想要的字符串来代替“half” - 唯一的标准是具有相同值的所有列将具有相同的宽度。

关于python - Tkinter 网格权重的表现不符合我的预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46199942/

相关文章:

python - 将新列添加到可变长度的数据框中

python - 如何在 python 中验证条目小部件?

python - 用不同的 __new__ 签名为 child 实例化 __new__ 中的 child

python - Conda 更新给出了复杂的依赖项名称,不像 py36_0

python - 为什么我的reverse()方法在python 3中不起作用?

python-3.x - Marvel 开发者 API 调用,仅收到一页

javascript - 转译预处理器

python - a 是什么意思? Python 中的 import 语句是什么意思?

python - 如何管理 "NavigationToolbar2TkAgg"工具栏的位置?

python - 循环之神再次来袭——如何在 GUI mainloop 的情况下保持套接字连接?