Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
900 views
in Technique[技术] by (71.8m points)

python - Find specific widget at tkinter inferface

I know that there's another question like this but this one is not a duplicate.

The problem is to find a specific widget (or widgets) by its type, maybe that required widget is not a sub-widget.

I make this question because i did not find something like this (did not search too much) and can be useful to someone.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Basically, because it’s no way to know if the required widget is a sub-widget, it’s not a bad idea to start from root.

# This function receives a widget and iterates to find root
def get_root(widget):
    parent_name = ''
    while parent_name != '.':  # root widget's name is '.'
        parent_name = widget.winfo_parent()  # Here get the current widget parent
        widget = widget._nametowidget(parent_name)  # Using the name, it turns into a widget

    # Returns root widget
    return widget

Once the root reference is obtained, then search all sub-widgets (children), the following method is from this question:

# This function returns a list of desired widgets
def find_widget(some_widget, desired_widget):
    root = get_root(some_widget)  # Obtains root
    _list = root.winfo_children()  # Obtains root's children
    desired_widget_list = []  #  Here will be all the widgets that match with your desired widget type
    for item in _list:
        #  If some widget have children, then all of them will be append into _list
        if item.winfo_children():
            _list.extend(item.winfo_children())  # Appending widgets

        #  If some type widget in _list match with your desired widget
        #  then it will be inserted into desired_widget_list
        if '!' + desired_widget in str(item):
            desired_widget_list.insert(len(desired_widget_list), item)

    #  Return a list that contains all widgets that match with your desired widget type
    return desired_widget_list

Just need to have a reference of some widget that belongs the GUI and the widget type. It can be used like this:

find_widget(some_frame, 'frame')
find_widget(some_treeview, 'treeview')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...