Reputation: 914
I want to deactivate the button when user presses it. As there are lots of buttons in GUI that I'm making. I want to generalise this. I am doing it the following:
def deactivate (btn):
btn.configure(state='disabled')
print ('Button is deactivated')
return
Button = Tk.Button(root, text='click',command=lambda: deactivate (Button))
Above code is working fine for me, but nowhere I have seen anybody using this. So, I'm wondering, does this has complications going forward that I'm not aware of?
Upvotes: 0
Views: 242
Reputation: 46678
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.
Upvotes: 2