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

人走茶凉 提交于 2019-12-24 05:16:28

问题


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()

回答1:


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.



来源:https://stackoverflow.com/questions/25328787/can-you-pack-multiple-tkinter-widgets-at-a-time-rather-than-packing-them-individ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!