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

Python 如何在tkinter中选择小部件的所有实例?,python,tkinter,Python,Tkinter,那么是否有人知道一种“获取”所有标签的方法,例如从Tk中的程序或窗口。i、 e类似于root.winfo.children,但仅适用于一种小部件 另外,我知道您可以使用列表,但我想知道是否有更好的方法?您可以使用universalwinfo_toplevel()方法获取包含任何小部件的顶级窗口,并过滤winfo_children()返回的项目类,以便它只包含所需类型的小部件。下面是一个这样做的示例: from pprint import pprint import tkinter as tk

那么是否有人知道一种“获取”所有标签的方法,例如从Tk中的程序或窗口。i、 e类似于root.winfo.children,但仅适用于一种小部件


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

您可以使用universal
winfo_toplevel()
方法获取包含任何小部件的顶级窗口,并过滤
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()

你为什么说更好?列表有什么问题?这只会返回直接的后代。它不会在整个应用程序中找到所有标签(除非整个应用程序的根目录中有所有小部件)。@Bryan:像往常一样,这一点很好。我认为我的最新答案解决了这个问题。