Can you pack multiple Tkinter widgets at a time rather than packing them individually?
Asked Answered
M

1

5

You create an initial root window and then multiple widgets (such as Labels, Buttons, Events).

You have to pack each one of them and can do it in several ways that I'm aware of.

Button(root, text="Button1", command=something).pack()

or

btn1 = Button(root, text="Button1", command=something)
btn1.pack()

Is it possible to pack multiple widgets that are assigned to "root" in one swoop without using a for loop and explicitly naming the items, like this:

for item in [btn1, btn2, label1, label2]:
    item.pack()
Monophyletic answered 15/8, 2014 at 14:58 Comment(0)
M
7

You could use root.children to get all the buttons and labels added to that parent element and then call the pack function for those. children is a dictionary, mapping IDs to actual elements.

root = Tk()

label1  = Label(root, text="label1")
button1 = Button(root, text="button1")
label2  = Label(root, text="label2")
button2 = Button(root, text="button2")

for c in sorted(root.children):
    root.children[c].pack()

root.mainloop()

This will pack all those buttons and labels underneath each other, from top to bottom, in the same order as they where added to the parent element (due to sorted). Note, however, that the usefulness of this is rather limited, since normally you'd not just place all your widgets in one column.

Mylonite answered 15/8, 2014 at 15:30 Comment(1)
In Python 3.12, I don't need to use sorted(root.children) because that's actually in reverse order.Ity

© 2022 - 2024 — McMap. All rights reserved.