繁体   English   中英

按下后如何禁用按钮?

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

我想在按下 Tkinter 按钮后禁用它。

这是我到目前为止的努力:

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()

您需要 1) 跟踪您的按钮(因此将其存储为 class 变量)和 2) 通过其state属性更改按钮 state。

假设您将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)

您可以使用.config(state="disabled")禁用该按钮。 最好为按钮的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")

请注意, button已更改为实例变量self.button ,以便可以在新的 function 中访问它。

暂无
暂无

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

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