I have 5 buttons in my program and all of them need to set a single variable.
I could make an separate function function for all of them but i thought there should be an better way to so.
So I tried the following:
self.__Button1 = tk.Button(self.parent,text='Start', command=lambda: (start_flag = True)).pack()
But this doesnt work. Is there an way to do this or maybe other easy way to all set there own variable (start_flag is one of them)?
Thanks in regards
Update:
With novel's comment i tried the following: But this doesnt work so i will just make 5 almost the same functions as furas suggested.
def setarr(self, *args, flag, bool):
# set flag according to button press
print(flag)
flag = bool
The normal way to do this is to create a function that takes a single argument, and sets the variable based on a passed-in parameter. You can use either lambda
or functools.partial
to create the button command:
import Tkinter as tk
class Example(object):
def __init__(self):
self.root = tk.Tk()
self.variable = None
self.button1 = tk.Button(self.root, text="One",
command=lambda: self.set_variable(1))
self.button2 = tk.Button(self.root, text="Two",
command=lambda: self.set_variable(2))
self.label = tk.Label(self.root, text="", width=20)
self.label.pack(side="top", fill="x")
self.button1.pack(side="top")
self.button2.pack(side="top")
def start(self):
self.root.mainloop()
def set_variable(self, value):
self.variable = value
self.label.configure(text="variable = %s" % self.variable)
example = Example()
example.start()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.