I am trying to figure out exactly how to implement a callback function which does something more meaningful than just print output. I am fairly inexperienced, so I am not sure how callback functions should or can be implemented in Python (or in any other language, for that matter).
Consider the following Python code:
from Tkinter import *
def callbackfunc(*args):
print "Hello World!"
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
optionvalue = IntVar(master)
optionvalue.set(2)
optionvalue.trace("w", callbackfunc)
self.optionmenu = OptionMenu(master, optionvalue, 1, 2, 3, 4)
self.optionmenu.pack()
I am trying to implement an OptionMenu (a Tkinter widget) such that when its selected value is changed, my callback function does something meaningful—more specifically, it will change a global variable value, defined somewhere else in the program. As it is implemented above, it simply prints output (albeit successfully).
I cannot figure out how to pass parameters to my callback function. I do not want this particular callback function to return anything; however, I am curious as to how I would make my callback function return something, and how I would implement the rest of my program so that it could utilize those returned results, whatever those might be. Am I trying to implement a Python callback function in a way in which it was not intended to be implemented? If not, how do I make this one work?
It’s a little bit unclear what you mean by “pass parameters to my callback function.” You’re already doing that! For example:
When run…
So you see, when Tkinter calls your callback, it passes parameters to it. If you wanted to do something other than print them, you could store them in some state, by passing a method instead of a function.
When run…
Also, perhaps you want to access the value of
optionvalue. You could save a reference to it then:When run…
You could also use
root.getvar(name)withname = 'PY_VAR0'(the first arg passed to the callback), as noob oddy suggests.