Reputation: 343
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?
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. 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.
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!
Note: I'm using Python v3.8.5
Upvotes: 2
Views: 280
Reputation: 385840
Why is the spacing uneven as in output #2?
The reason is because you are three columns a weight of 1 even though you're only using two columns.
If your goal is three equal sized columns, you should be using the uniform
option. weight
only applies to unused space, it in no way guarantees equal sized columns.
To get three equal sized columns, set uniform
to the same value for all three columns. 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:
Upvotes: 2