如何在tkinter中选择小部件的所有实例?

时间:2018-09-24 17:17:30

标签: python tkinter

因此,没有人知道一种“获取”所有标签的方法,例如从Tk中的程序或窗口中获取。即类似于root.winfo.children,但仅适用于一种小部件。

我也知道您可以使用列表,但是我想知道是否有更好的方法?

1 个答案:

答案 0 :(得分:1)

您可以使用通用的winfo_toplevel()方法来获取包含任何小部件的顶级窗口,并使用list comprehension来过滤winfo_children()返回的项的类,使其仅包含小部件所需类型的。这是执行此操作的示例:

from pprint import pprint
import tkinter as tk


class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.grid()
        self.createWidgets()

    def createWidgets(self):
        self.quitButton = tk.Button(self, text='Test', command=self.find_buttons)
        self.quitButton.grid()
        nested_frame = tk.Frame(self)  # Nest some widgets an extra level for testing.
        self.quitButton = tk.Button(nested_frame, text='Quit', command=self.quit)
        self.quitButton.grid()
        nested_frame.grid()

    def find_buttons(self):
        WIDGET_CLASSNAME = 'Button'
        toplevel = self.winfo_toplevel()  # Get top-level window containing self.
        # Use a list comprehension to filter result.
        selection = [child for child in get_all_children(toplevel)
                        if child.winfo_class() == WIDGET_CLASSNAME]
        pprint(selection)


def get_all_children(widget):
    """ Return a list of all the children, if any, of a given widget.  """
    result = []  # Initialize.
    return _all_children(widget.winfo_children(), result)


def _all_children(children, result):
    """ Recursively append all children of a list of widgets to result. """
    for child in children:
        result.append(child)
        subchildren = child.winfo_children()
        if subchildren:
            _all_children(subchildren, result)

    return result


app = Application()
app.master.title('Sample application')
app.mainloop()