我查阅了文档并在 columnconfigure 中找到了 3 个可行的选项:
- 最小化
- 垫
- 体重
但是如果您想让列尽可能小怎么办?
我有 3 个复选按钮,我想并排排列。
我发现的工作是:
weekly.grid(row = 2, column = 1, sticky = W)
monthly.grid(row = 2, column = 1, padx = 75, sticky = W)
yearly.grid(row = 2, column = 1, padx = 150, sticky = W)
有没有更“漂亮”的方法来做到这一点?
(可能值得一提的是,当使用第 2 列和第 3 列时,它们被分隔得太多了 :-()
最好的问候,
卡斯珀
最佳答案
使用网格几何管理器的默认行为是列将尽可能小,因此您无需执行任何操作(假设您正确使用网格)。
您描述的元素之间空间太大的行为可能是因为您在同一列中有其他更宽的小部件。该列将默认为容纳最宽项目的最小宽度。那个,或者在你的代码的其他地方,你给一些导致它们扩展的列一个非零的权重。
在我谈论解决方案之前,让我确定清楚您使用网格将多个小部件放在同一个单元格中的方式绝对是错误的做法。绝对没有理由诉诸这样的解决方案。一般的经验法则是,您永远不应在一个单元格中放置一个以上的小部件。
对您来说最简单的解决方案是组合网格和包。将所有复选按钮放在一个框架中,并将它们打包在该框架的左侧。然后,使用 sticky="w"
将框架放入您的网格中。然后,无论窗口有多大,复选按钮都将始终固定在其包含框架的左侧。
请注意,此解决方案并未违反我之前提到的经验法则。您只将一个小部件放在一个单元格中:框架。您可以在该内部框架中放置任何您想要的内容,但从网格的角度来看,网格的每个单元格中只有一个小部件。
这是一个基于 python 2.7 的工作示例:
import Tkinter as tk
class ExampleView(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
cbframe = tk.Frame(self)
cb1 = tk.Checkbutton(cbframe, text="Choice 1")
cb2 = tk.Checkbutton(cbframe, text="Choice 2")
cb3 = tk.Checkbutton(cbframe, text="Choice 3")
cb1.pack(side="left", fill=None, expand=False)
cb2.pack(side="left", fill=None, expand=False)
cb3.pack(side="left", fill=None, expand=False)
# this entry is for illustrative purposes: it
# will force column 2 to be widget than a checkbutton
e1 = tk.Entry(self, width=20)
e1.grid(row=1, column=1, sticky="ew")
# place our frame of checkbuttons in the same column
# as the entry widget. Because the checkbuttons are
# packed in a frame, they will always be "stuck"
# to the left side of the cell.
cbframe.grid(row=2, column=1, sticky="w")
# let column 1 expand and contract with the
# window, so you can see that the column grows
# with the window, but that the checkbuttons
# stay stuck to the left
self.grid_columnconfigure(1, weight=1)
if __name__ == "__main__":
root = tk.Tk()
view = ExampleView(root)
view.pack(side="top", fill="both", expand=True)
root.wm_geometry("400x200")
root.mainloop()
当然,您也可以将复选按钮放在单独的列中——这通常是最简单的——但您可能需要让其他行中的其他项目跨越多个列并处理列权重。由于根据您的描述并不清楚您的问题到底是什么,上述解决方案可能对您来说是最简单的。
关于python - Tkinter 配置列宽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14045271/