【问题标题】:Can you pack multiple Tkinter widgets at a time rather than packing them individually?您可以一次打包多个 Tkinter 小部件而不是单独打包它们吗?
【发布时间】:2014-08-15 14:58:01
【问题描述】:

您创建一个初始根窗口,然后创建多个小部件(例如标签、按钮、事件)。

您必须将它们中的每一个都打包,并且可以通过我知道的几种方式来完成。

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

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

是否可以一次性打包多个分配给“root”的小部件无需使用 for 循环并显式命名项目,如下所示:

for item in [btn1, btn2, label1, label2]:
    item.pack()

【问题讨论】:

    标签: python tkinter pack


    【解决方案1】:

    您可以使用root.children 来获取添加到该父元素的所有按钮和标签,然后为它们调用pack 函数。 children 是一个字典,将 ID 映射到实际元素。

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

    这将pack所有这些按钮和标签从上到下,与它们添加到父元素的顺序相同(由于sorted)。但是请注意,这样做的用处相当有限,因为通常您不会将所有小部件放在一列中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-13
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-24
      相关资源
      最近更新 更多