I want to disable a Tkinter button after I pressed it.
This is my effort so far:
class Pag4(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Alege prelucrarea")
label.pack(pady=10,padx=10)
self.controller = controller
label = tk.Label(self, text="Pagina 4")
button = tk.Button(self, text="Srunjire", command=lambda: controller.show_frame("Pag20"))
button.pack()
You need 1) to track your button (so store it as class variable) and 2) to change button state via its state
property.
Assuming you attach manage_button
function to the button, your code becomes this:
def enable_button(button:tk.Button):
button["state"] = "normal"
def disable_button(button:tk.Button):
button["state"] = "disabled"
class Pag4(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Alege prelucrarea")
label.pack(pady=10,padx=10)
self.controller = controller
label = tk.Label(self, text="Pagina 4")
self.button = tk.Button(self, text="Srunjire", command=lambda: controller.show_frame("Pag20"))
self.button.pack()
def manage_button():
if self.button.cget("state") == "normal":
disable_button(self.button)
else:
enable_button(self.button)
You can use .config(state="disabled")
to disable the button. Better create a new function for the command
option of the button and then disable the button and call controller.show_frame(...)
inside that new function:
class Pag4(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Alege prelucrarea")
label.pack(pady=10,padx=10)
self.controller = controller
label = tk.Label(self, text="Pagina 4") # note that this label is not visible
self.button = tk.Button(self, text="Srunjire", command=self.on_button_clicked)
self.button.pack()
def on_button_clicked(self):
self.button.config(state="disabled")
self.controller.show_frame("Pag20")
Note that button
is changed to instance variable self.button
so that it can be accessed inside the new function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.