首页 > 解决方案 > 如何在按下按钮时更改按钮颜色并在按下其他按钮时更改为原始颜色。按钮是使用 python 中的类创建的

问题描述

我使用 python 类创建按钮。假设它有 10 个相同类别的按钮。当我按下第一个按钮时,第一个按钮的颜色应更改为“红色”。当我按下第二个按钮时。第一个按钮的颜色应恢复为原始颜色,第二个按钮的颜色应更改为红色。现在说,如果我按下第 8 个按钮,那么第 2 个按钮的颜色应该恢复到原来的颜色,第 8 个按钮的颜色现在应该是“红色”

这是实现的类:

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')

标签: pythonpython-3.x

解决方案


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")

推荐阅读