pythonwidgettkinter

How to detect when an OptionMenu or Checkbutton change?


My tkinter application has several controls, and I'd like to know when any changes occur to them so that I can update other parts of the application.

Is there anything that I can do short of writing an updater function, and looping at the end with:

root.after(0, updaterfunction) 

This method has worked in the past but I'm afraid that it might be expensive if there are many things to check on.

Even if I did use this method, could I save resources by only updating items with changed variables? If so, please share how, as I'm not sure how to detect specific changes outside of the update function.


Solution

  • Many tkinter controls can be associated with a variable. For those you can put a trace on the variable so that some function gets called whenever the variable changes.

    Example:

    In the following example the callback will be called whenever the variable changes, regardless of how it is changed.

    def callback(*args):
        print(f"the variable has changed to '{var.get()}'")
    
    root = tk.Tk()
    var = tk.StringVar(value="one")
    var.trace("w", callback)
    

    For more information about the arguments that are passed to the callback see this answer