Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 692
Amarok Avatar asked Mar 15 '11 06:03

Amarok


People also ask

How do I get OptionMenu value?

Python Tkinter OptionMenu get value So to know the option selected by a user we use the get() method. get() is applied on the variable assigned to the OptionMenu and it returns the currently selected option in the OptionMenu.

Which syntax is used to create drop down menu in python?

Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method.


1 Answers

If you are using a Tkinter Variable class like StringVar() for storing the variables in your Tkinter OptionMenu or Checkbutton, you can use its trace() method.

trace(), basically, monitors the variable when it is read from or written to.

The trace() method takes 2 arguments - mode and function callback.

trace(mode, callback)

  • The mode argument is one of “r” (call observer when variable is read by someone), “w” (call when variable is written by someone), or “u” (undefine; call when the variable is deleted).
  • The callback argument is the call you want to make to the function when the variable is changed.

This is how it is used -

def callback(*args):
    print("variable changed!")

var = StringVar()
var.trace("w", callback)
var.set("hello")

Source : http://effbot.org/tkinterbook/variable.htm

like image 131
shawn1912 Avatar answered Nov 03 '22 01:11

shawn1912