如何在按下按钮时将其颜色更改为原始颜色,并在按下其他按钮时将颜色更改为原来的颜色.按钮是使用python中的类创建的



我使用python类创建按钮。假设它有10个同类按钮。当我按下第一个按钮时,第一个按钮的颜色应该改为"红色"。当我按下第二个按钮时。第一个按钮的颜色应该恢复到原来的颜色,第二个按钮的色彩应该改为红色。现在说,如果我按下第八个按钮,那么第二个按键的颜色应该还原到原来的色彩,第八个按键的色彩现在应该是"红色">

这是实现的类:

class CreateButton:
def __init__(self,Button_name,Data):
self.Data=Data
self.Button=tk.Button(delscframe.interior, height=1, width=28, 
relief=tk.FLAT, 
bg='light blue', fg="black",
font="arial 12 bold", text=Button_name,
command=self.OutputText)
self.Button.pack(padx=5, pady=2, side=tk.TOP)       
def OutputText(self):
self.Button.config(fg='red',bg='light blue')
Buttons = [] # list to store all buttons
class CreateButton:
def __init__(self,Button_name, Data, index):
self.index = index
self.Data=Data
self.Button=tk.Button(delscframe.interior, height=1, width=28, 
relief=tk.FLAT, 
bg='light blue', fg="black",
font="arial 12 bold", text=Button_name,
command=lambda:setRed(self.index))
self.Button.pack(padx=5, pady=2, side=tk.TOP) 
def OutputText(self, col):
self.Button.config(fg=col)
for i in range(10):
btn = CreateButton("name", i)
Buttons.append(btn) # insert buttons into list
def setRed(index):
for i in range(10):
if i == index: # thats the clicked button - make it red
Buttons[index].OutputText("red")
else: # all other should be black
Buttons[i].OutputText("black")

最新更新