您不必像我所做的那样将整个应用程序包装在一个类中,甚至不必使用静态方法。关键是你有某种回调函数会在按下按钮时触发。作为回调函数调用的一部分,您还将按下的按钮对象的引用传递给回调。还有其他方法可以做到这一点,但我认为传递对按钮本身的引用是最有意义的:
import tkinter as tk
class Application(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title("Buttons")
self.resizable(width=False, height=False)
number_of_rows = 8
number_of_columns = 8
for y in range(number_of_rows):
for x in range(number_of_columns):
button = tk.Button(self, text=f"{x}, {y}")
button.config(command=lambda button=button: Application.on_button_click(button))
button.grid(column=x, row=y)
@staticmethod
def on_button_click(button):
button.config(bg="green")
print(f"You clicked on {button['text']}")
def main():
application = Application()
application.mainloop()
return 0
if __name__ == "__main__":
import sys
sys.exit(main())