To do that you need to pass the Button object "b" into the callback function. In order to do that you need to set the command on the next line, so that the "b" object is available. Like this:
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()
But actually this would be a great place to learn about subclasses. You can modify tkinter's Button to make your own type of Button that does what you want in addition to it's normal actions:
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()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…