python - 如何在按下按钮时更改按钮颜色并在按下其他按钮时更改为原始颜色。按钮是使用 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')
解决方案
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")
推荐阅读
- java - 从 Java 读取来自 MQ 的所有消息的问题
- assembly - 使用 GNU 汇编器宏的“表达式后的垃圾”
- javascript - Safari css错误的元素高度
- xamarin - Xamarin Forms,ZXingBarcodeImageView 模糊
- curl - 使用 cURL 将 jenkins 作业从一个视图移动到另一个视图的命令
- leaflet - Mapbox:在给定两个 OSM 节点 ID 的情况下制作一条线
- python - 如何通过 Python 正则表达式从 arp 输出中获取 ip 地址和 mac 地址?
- highcharts - Highchart 不连接线
- php - 如何使用php用新值更新json数据标签的值?
- c# - 如何通过c#中的反射获取特定类型实例(不是对象类型)