[英]How to make the spacing between two widgets displayed in a 3 column grid equal in tkinter?
The following code, which loops thrice to create three label widgets,以下代码循环三次以创建三个标签小部件,
import tkinter as tk
root = tk.Tk()
root.geometry("400x200")
frm = tk.Frame(master=root, bg="yellow")
frm.columnconfigure(index=(0, 1, 2), weight=1)
for i in range(3):
tk.Label(master=frm, text=i, bg="red", padx=40, pady=10).grid(row=0, column=i)
frm.pack(fill="both", expand=True)
root.mainloop()
gives the following output (as one would expect):给出以下输出(正如人们所期望的):
But, the following code, which only loops twice to create two label widgets,但是,以下代码只循环两次以创建两个标签小部件,
import tkinter as tk
root = tk.Tk()
root.geometry("400x200")
frm = tk.Frame(master=root, bg="yellow")
frm.columnconfigure(index=(0, 1, 2), weight=1)
for i in range(2):
tk.Label(master=frm, text=i, bg="red", padx=40, pady=10).grid(row=0, column=i)
frm.pack(fill="both", expand=True)
root.mainloop()
Gives this output:给出这个输出:
As you can see, the two widgets are not properly spaced out.如您所见,两个小部件没有正确间隔开。 I wanted to get this kind of output:
我想得到这种输出:
How do I achieve this?我如何实现这一目标? Why is the spacing uneven as in output #2?
为什么输出 #2 中的间距不均匀?
Please keep in mind that I want to do this without creating any other label widgets as I am using a similar method to display search results in an application that I'm making using tkinter.请记住,我想在不创建任何其他标签小部件的情况下执行此操作,因为我使用类似的方法在我使用 tkinter 制作的应用程序中显示搜索结果。 I asked this question because I am facing the same issue in that application when I try to display only two search results or only one search result.
我问这个问题是因为当我尝试仅显示两个搜索结果或仅显示一个搜索结果时,我在该应用程序中面临同样的问题。
Thanks in advance for answering!预先感谢您的回答! And please bare with me as I'm only a beginner at tkinter.
请原谅我,因为我只是 tkinter 的初学者。
PS: I know this deviates a bit from the question, but if you can point me to some sources/tutorials where I could better learn more about how tkinter works, please do! PS:我知道这与问题有点不同,但如果您能指出一些来源/教程,我可以更好地了解有关 tkinter 工作原理的更多信息,请这样做!
Note: I'm using Python v3.8.5注意:我使用的是 Python v3.8.5
Why is the spacing uneven as in output #2?
为什么输出 #2 中的间距不均匀?
The reason is because you are three columns a weight of 1 even though you're only using two columns.原因是因为即使您只使用两列,您也是三列,权重为 1。
If your goal is three equal sized columns, you should be using the uniform
option.如果您的目标是三个大小相等的列,则应使用
uniform
选项。 weight
only applies to unused space, it in no way guarantees equal sized columns. weight
仅适用于未使用的空间,它绝不保证大小相等的列。
To get three equal sized columns, set uniform
to the same value for all three columns.要获得三个大小相等的列,请将所有三列的
uniform
值设置为相同的值。 It doesn't matter what the value is, as long as it's the same for all columns.值是什么并不重要,只要所有列都相同即可。
frm.columnconfigure(index=(0, 1, 2), weight=1, uniform="equal")
This is the result:这是结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.