我假设您使用 range() 函数循环以创建所有网格按钮。
在以下 OOP 代码中,您都可以一键更改所有内容,
还可以将鼠标悬停在每种颜色上并更改颜色:
注意:
- 点击白色按钮会将所有内容变为绿色
- 将鼠标悬停在每种颜色上会将其变为蓝色
from tkinter import *
root = Tk()
def change_myself(button,color_in_hex):
button.configure(bg = color_in_hex)
class MyButtons():
def __init__(self,current_color,new_color,button_amount):
super(MyButtons,self).__init__()
self._current_color = current_color
self._new_color = new_color
self._button_amount = button_amount
self._buttons_list = list(range(self._button_amount))
@property
def buttons_list(self):
return self._buttons_list
def __getitem__(self, item):
return item
def __setitem__(self, key, value):
self._buttons_list = value
def create_buttons(self):
for a in range(self._button_amount):
self.buttons_list[a] = Button(root,bg = self._current_color,text = 'Button Number {0}'.format(a))
print(self.buttons_list[a])
self.buttons_list[a].grid(row = a,column = 0)
self.buttons_list[a].bind('<Enter>',lambda event,current_button_index = a: self._buttons_list[current_button_index].configure(bg = '#0000FF'))
special_button = Button(root,bg = '#FFFFFF',text = 'Changer!')
special_button.grid(row = 0,column = 1)
special_button.bind('<Button-1>',lambda event: self.change_everything())
def change_everything(self):
for button in self.buttons_list:
button.configure(bg = self._new_color)
implementation = MyButtons(current_color = '#FF0000',new_color = '#00FF00',button_amount = 10)
implementation.create_buttons()
root.mainloop()
结果如下: