Your implementation is fine. But as you said there will be a lot of buttons having same feature, then I would suggest to create a custom Button class (inherited from tk.Button
) to embed this feature and use this custom Button class for those buttons requiring this feature.
Below is an example:
import tkinter as tk
class MyButton(tk.Button):
def __init__(self, parent=None, *args, **kw):
self._user_command = kw.pop("command", None)
super().__init__(parent, *args, **kw)
self["command"] = self._on_click
def _on_click(self):
self.configure(state="disabled")
if self._user_command:
self._user_command(self)
def on_click(btn):
print (f'Button "{btn["text"]}" is deactivated')
root = tk.Tk()
button1 = MyButton(root, text='click', command=on_click)
button1.pack()
button2 = MyButton(root, text='Hello', command=on_click)
button2.pack()
root.mainloop()
Note that I have changed the callback signature for command
option. The instance of the button will be passed to callback as the first argument, so that you can do whatever you want on the button.