为此,您需要将 Button 对象“b”传递给回调函数。为此,您需要在下一行设置命令,以便“b”对象可用。像这样:
from tkinter import *
root = Tk()
def change_to_red(bttn):
bttn.config(bg='red', activebackground='red') # same as bttn['bg'] = 'red'; bttn['activebackground'] = 'red'
print(bttn['text'])
btn = [i for i in range(10)]
for i in range(len(btn)):
b = Button(root, text=str(i), width=6)
b.config(command=lambda c=b: change_to_red(c))
b.pack()
root.mainloop()
但实际上这将是学习子类的好地方。您可以修改 tkinter 的 Button 以制作您自己的 Button 类型,除了正常操作之外,它还可以执行您想要的操作:
import tkinter as tk
class Desync192Button(tk.Button):
def __init__(self, master=None, **kwargs):
self.command = kwargs.pop('command', None)
super().__init__(master, command=self.on_click, **kwargs)
def on_click(self):
self.config(bg='red', activebackground='red')
if self.command: self.command()
# demo:
root = tk.Tk()
for i in range(10):
b = Desync192Button(root, text=i, width=6, command=lambda c=i: print(c))
b.pack()
root.mainloop()