简体   繁体   English

按下后如何禁用按钮?

[英]How can I disable a button after pressed?

I want to disable a Tkinter button after I pressed it.我想在按下 Tkinter 按钮后禁用它。

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.您需要 1) 跟踪您的按钮(因此将其存储为 class 变量)和 2) 通过其state属性更改按钮 state。

Assuming you attach manage_button function to the button, your code becomes this:假设您将manage_button function 附加到按钮,您的代码将变为:

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.您可以使用.config(state="disabled")禁用该按钮。 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:最好为按钮的command选项创建一个新的 function,然后禁用该按钮并在新的 function 中调用controller.show_frame(...)

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.请注意, button已更改为实例变量self.button ,以便可以在新的 function 中访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM