如何仅使用一个函数(tkinter python)更改多个按钮文本



我想只使用一个函数(self.toggle)为我所有的按钮在我的GUI,而不是做每一个按钮。我试过改变自己的名字。按钮只有没有数字,然后我有文字改变只有一个按钮,而不是一个需要的。有没有简单的方法只做一个函数?我从Python开始。提前谢谢。

from tkinter import *
from tkinter.ttk import Button
class Application(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
self.create_widgets()
self.number = [1, 2, 3]
self.mainloop()
def toggle1(self, number):
if self.button1.config('text')[-1] == f"{number}: ON":
self.button1.config(text=f"{number}: OFF")
print("OFF")
else:
self.button1.config(text=f"{number}: ON")
print("ON")
def toggle2(self, number):
if self.button2.config('text')[-1] == f"{number}: ON":
self.button2.config(text=f"{number}: OFF")
print("OFF")
else:
self.button2.config(text=f"{number}: ON")
print("ON")
def toggle3(self, number):
if self.button3.config('text')[-1] == f"{number}: ON":
self.button3.config(text=f"{number}: OFF")
print("OFF")
else:
self.button3.config(text=f"{number}: ON")
print("ON")
def create_widgets(self):
self.title("application")
width = 200
height = 250
screen_width = self.winfo_screenwidth()
screen_height = self.winfo_screenheight()
x = (screen_width/2) - (width/2)
y = (screen_height/2) - (height/2)
self.geometry("%dx%d+%d+%d" % (width, height, x, y))
self.button1 = Button(self, text = "1: OFF", command=lambda: self.toggle1(1))
self.button1.grid(
row=3, column=0, sticky="w", columnspan=1, padx=0, pady=10)
self.button2 = Button(self, text = "2: OFF", command=lambda: self.toggle2(2))
self.button2.grid(
row=5, column=0, sticky="w", columnspan=1, padx=0, pady=10)
self.button3 = Button(self, text = "3: OFF", command=lambda: self.toggle3(3))
self.button3.grid(
row=7, column=0, sticky="w", columnspan=1, padx=0, pady=10)

if __name__ == "__main__":
Application()

您可以将按钮小部件传递给toggle(),如下所示:

...
class Application(Tk):
...
def toggle(self, button):
number, state = button['text'].split(': ')
state = 'ON' if state == 'OFF' else 'OFF'
button['text'] = f'{number}: {state}'
print(number, state)
def create_widgets(self):
...
self.button1 = Button(self, text="1: OFF", command=lambda: self.toggle(self.button1))
...
self.button2 = Button(self, text="2: OFF", command=lambda: self.toggle(self.button2))
...
self.button3 = Button(self, text="3: OFF", command=lambda: self.toggle(self.button3))
...

相关内容

  • 没有找到相关文章

最新更新