Tkinker网格权重不符合我的预期

时间:2017-09-13 14:17:04

标签: 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()

2 个答案:

答案 0 :(得分:3)

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

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

如果你使窗口变大(通过交互式调整大小,使用geometry方法或通过缩放窗口),tkinter将使用权重来决定如何分配 extra 空间。

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

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

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

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

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

答案 1 :(得分:0)

网格权重分配额外空间。请参阅reference

  

weight要使列或行可伸缩,请使用此选项   提供一个值,该值给出此列或行的相对权重   分配额外空间时。例如,如果小部件w包含   一个网格布局,这些线将分配额外的四分之三   空间到第一列,四分之一到第二列:

w.columnconfigure(0, weight=3)
w.columnconfigure(1, weight=1)

文本小部件的默认大小远远大于其他内容的默认大小。如果你想要更多相等的列,你必须增加其他东西并缩小文本。

相关问题