简体   繁体   中英

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?

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

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:

截屏

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM