I want to change the value of a variable just with a button, i don’t want to create a new entire function just like that:
from Tkinter import * variable = 1 def makeSomething(): global variable variable = 2 root = Tk() myButton = Button(root, text='Press me',command=makeSomething).pack()
How i can do that? (I need to do that for six buttons, making six functions it’s not an option)
Advertisement
Answer
i need to make this for 6 buttons…
If each button modifies the same global variable, then have makeSomething
accept a value
parameter:
from Tkinter import * variable = 1 def makeSomething(value): global variable variable = value root = Tk() Button(root, text='Set value to four',command=lambda *args: makeSomething(4)).pack() Button(root, text='Set value to eight',command=lambda *args: makeSomething(8)).pack() Button(root, text='Set value to fifteen',command=lambda *args: makeSomething(15)).pack() #...etc
If each button modifies a different global, then condense all your globals into a single global dict, which makeSomething
can then modify.
from Tkinter import * settings = {"foo": 1, "bar": 1, "baz": 1} def makeSomething(name): settings[name] = 2 root = Tk() Button(root, text='Set foo',command=lambda *args: makeSomething("foo")).pack() Button(root, text='Set bar',command=lambda *args: makeSomething("bar")).pack() Button(root, text='Set baz',command=lambda *args: makeSomething("baz")).pack() #...etc
In either case, you still only require one function.
By the way, don’t do this:
myButton = Button(root).pack()
This assigns the result of pack()
to myButton, so myButton will be None
instead of referring to your button. Instead, do:
myButton = Button(root) myButton.pack()
6 People found this is helpful