How do I disable all the user input widgets (butto

2020-04-16 03:41发布

I am designing a GUI using Python and Tkinter. All the buttons and entries required to register the user input commands are placed inside a main frame and are their child widgets.

I want to know if it is possible to disable all the input functionality from these widgets by propagating some "disable" flag from the main frame to all the input widgets. In this way, I was hoping to be able to toggle their state in a single line of code.

I believe that should be possible. Does anyone know how to do this?

1条回答
狗以群分
2楼-- · 2020-04-16 03:53

Tk widgets have a state configuration option that can be either normal or disabled. So you can set all children of a frame to disabled using the winfo_children method on the frame to iterate over them. For instance:

for w in app.winfo_children():
    w.configure(state="disabled")

Ttk widgets have state method which might require alternative handling. You may also want to set the takefocus option to False as well although I think that disabled widgets are automatically skipped when moving the focus (eg: by hitting the Tab key).

Edit

You can use the winfo_children and winfo_parent methods to walk the widget tree in both directions if necessary to access widgets contained in child frames for instance. For example, a simple function to visit each child of a root widget:

def visit_widgets(root, visitor):
  visitor(root)
  for child in root.winfo_children():
    visit_widgets(child, visitor)

from __future__ import print_function
visit_widgets(app, lambda w: print(str(w)))
查看更多
登录 后发表回答