I would like to use only one function (self.toggle) for all of my buttons in my GUI instead of doing each for every button. I have tried to change name of self.button only without numbers and then I had text changing on just one button not the one required. Is there simple way to do just one function? I’m just starting with Python. Thanks in advance.
JavaScript
x
65
65
1
from tkinter import *
2
from tkinter.ttk import Button
3
4
class Application(Tk):
5
6
def __init__(self, *args, **kwargs):
7
Tk.__init__(self, *args, **kwargs)
8
self.create_widgets()
9
self.number = [1, 2, 3]
10
self.mainloop()
11
12
def toggle1(self, number):
13
14
if self.button1.config('text')[-1] == f"{number}: ON":
15
self.button1.config(text=f"{number}: OFF")
16
print("OFF")
17
else:
18
self.button1.config(text=f"{number}: ON")
19
print("ON")
20
21
def toggle2(self, number):
22
23
if self.button2.config('text')[-1] == f"{number}: ON":
24
self.button2.config(text=f"{number}: OFF")
25
print("OFF")
26
else:
27
self.button2.config(text=f"{number}: ON")
28
print("ON")
29
30
def toggle3(self, number):
31
32
if self.button3.config('text')[-1] == f"{number}: ON":
33
self.button3.config(text=f"{number}: OFF")
34
print("OFF")
35
else:
36
self.button3.config(text=f"{number}: ON")
37
print("ON")
38
39
def create_widgets(self):
40
self.title("application")
41
42
width = 200
43
height = 250
44
screen_width = self.winfo_screenwidth()
45
screen_height = self.winfo_screenheight()
46
x = (screen_width/2) - (width/2)
47
y = (screen_height/2) - (height/2)
48
self.geometry("%dx%d+%d+%d" % (width, height, x, y))
49
50
self.button1 = Button(self, text = "1: OFF", command=lambda: self.toggle1(1))
51
self.button1.grid(
52
row=3, column=0, sticky="w", columnspan=1, padx=0, pady=10)
53
54
self.button2 = Button(self, text = "2: OFF", command=lambda: self.toggle2(2))
55
self.button2.grid(
56
row=5, column=0, sticky="w", columnspan=1, padx=0, pady=10)
57
58
self.button3 = Button(self, text = "3: OFF", command=lambda: self.toggle3(3))
59
self.button3.grid(
60
row=7, column=0, sticky="w", columnspan=1, padx=0, pady=10)
61
62
63
if __name__ == "__main__":
64
Application()
65
Advertisement
Answer
You can pass the button widget to toggle()
as below:
JavaScript
1
18
18
1
2
class Application(Tk):
3
4
def toggle(self, button):
5
number, state = button['text'].split(': ')
6
state = 'ON' if state == 'OFF' else 'OFF'
7
button['text'] = f'{number}: {state}'
8
print(number, state)
9
10
def create_widgets(self):
11
12
self.button1 = Button(self, text="1: OFF", command=lambda: self.toggle(self.button1))
13
14
self.button2 = Button(self, text="2: OFF", command=lambda: self.toggle(self.button2))
15
16
self.button3 = Button(self, text="3: OFF", command=lambda: self.toggle(self.button3))
17
18