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')
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…