Reputation: 223
I need to set some variables using tkinter callbacks on a tkinter Button. So I could say (inside of a class definition)
Button1 = Button(parentframe, text="set", command = self.setvar)
def setvar(self):
self.myvar = 7
Is there some way to do that with an inline (lambda) function, rather than cluttering things up with silly little callbacks?
command = lambda *args: something?
Upvotes: 0
Views: 355
Reputation: 10359
You could do something like this using Tkinter's integer variable class and a lambda function as you suspected. A variable of type IntVar
has .get()
and .set()
methods that will allow you to, unsurprisingly, get and set its value. Take the following for example:
from Tkinter import *
class App(Frame):
def __init__(self, *args, **kwargs):
Frame.__init__(self, *args, **kwargs)
# initialise Integer Variables
self.example1 = IntVar()
self.example1.set(2)
self.text1 = Entry(root, textvariable=self.example1, state=DISABLED)
self.text1.grid(row=0, column=0)
self.button1 = Button(root, text="Double", command=lambda: self.double_value(self.example1))
self.button1.grid(row=1, column=0)
def double_value(self, var):
var.set(var.get() * 2)
root = Tk()
app = App(root)
root.mainloop()
This gives you a bit of flexibility, and could be expanded to apply the same feature to multiple buttons relating to different Entry
boxes and IntVar
variables.
Upvotes: 1