当小部件跨越多列时,如何制作宽度相等的Tkinter列(Python 2.7)

在下文中,标有“ONE”,“TWO”和“THR”的按钮不会均匀分布.在我看来,问题的根源是Tk假定包含跨越多列的小部件的任何列的默认最小宽度.但是,此行为似乎没有记录,因此我不确定如何容纳或调整它以使列具有相等的宽度 – 包括文本小部件跨越的两列和文本未跨越的单列小部件 – 从而均匀地分隔按钮.我可以通过反复试验来克服它,即填充后一列,直到它与前两列匹配,但这似乎是一个糟糕的解决方案.

编辑:在下面与@ jwillis0720进行讨论后,我添加了一个额外的列(3)和按钮(‘FIV’)以使问题更加清晰.这个问题是关于如何在多列小部件跨越其中一些列而其他列不同的情况下使列具有相同的宽度.

import Tkinter

master = Tkinter.Tk()

Tkinter.Button(master, text='ONE').grid(row=0, column=0)
Tkinter.Button(master, text='TWO').grid(row=0, column=1)
Tkinter.Button(master, text='THR').grid(row=0, column=2)
Tkinter.Button(master, text='FOU').grid(row=1, column=2)
Tkinter.Button(master, text='FIV').grid(row=0, column=3) # added as per above edit
Tkinter.Text(master).grid(row=1, column=0, columnspan=2)

master.mainloop()

请注意,使用带有uniform的grid_columnconfigure并不能解决此问题.插入以下行(请参阅此处类似问题的答案:How to create equal-width columns in Python 2.7 with Tkinter)只会使列有弹性;它们仍然不均匀:

master.grid_columnconfigure(0, weight=1, uniform='a')
master.grid_columnconfigure(1, weight=1, uniform='a')
master.grid_columnconfigure(2, weight=1, uniform='a')
master.grid_columnconfigure(3, weight=1, uniform='a') # added as per above edit

解决方法:

我想你可能想要使用粘性选项.

sticky= Defines how to expand the widget if the resulting cell is
larger than the widget itself. This can be any combination of the
constants S, N, E, and W, or NW, NE, SW, and SE.

For example, W (west) means that the widget should be aligned to the
left cell border. W+E means that the widget should be stretched
horizontally to fill the whole cell. W+E+N+S means that the widget
should be expanded in both directions. Default is to center the widget
in the cell.

import Tkinter

master = Tkinter.Tk()

Tkinter.Button(master, text='ONE').grid(row=0, column=0, sticky='NW')
Tkinter.Button(master, text='TWO').grid(row=0, column=1, sticky='NW')
Tkinter.Button(master, text='THR').grid(row=0, column=2, sticky='NW')
Tkinter.Button(master, text='FOU').grid(row=1, column=2)
Tkinter.Text(master).grid(row=1, column=0, columnspan=2)


master.mainloop()

编辑

它是什么样子的.除了文本小部件占用指定的两列之外,我看起来像这样均匀分布.

上一篇:c – Vera TCL规则:列出所有局部变量


下一篇:论文笔记:HF-UNet