[Python] Tkinter, unable to disable/enable widget using the code from a tutorial [duplicate]

Discussão em 'Python' iniciado por Stack, Fevereiro 4, 2025.

  1. Stack

    Stack Membro Participativo

    I am using the following code (from a youtube tutorial) to enable and disable a widget in a tkinter window.

    However, I'm not getting the expected result. I am expecting the text widget to enable on the button click, but it starts as disabled and won't allow it to be enabled.

    What am I doing wrong?

    import tkinter as tk
    from tkinter import ttk

    class MainWindow(tk.Tk):
    def __init__(self):
    super().__init__()
    self.style = ttk.Style()
    self.create_main_frame().pack(expand=True)

    def on_enable_button_clicked(self):
    self.lbl_welcome.state(["!disabled"])

    def on_disable_button_clicked(self):
    self.lbl_welcome.state(["disabled"])

    def create_main_frame(self):
    frame_main = ttk.Frame(self)
    self.lbl_welcome = ttk.Label(frame_main,text="Testing")
    btn_enable = ttk.Button(frame_main,text="enable",command=self.on_enable_button_clicked())
    btn_disable = ttk.Button(frame_main,text="disable",command=self.on_disable_button_clicked())
    self.lbl_welcome.grid(row=0, column=0, columnspan=2)
    btn_enable.grid(row=1,column=0,padx=2,pady=(10,0))
    btn_disable.grid(row=1,column=1,padx=2,pady=(10,0))
    return frame_main

    def main():
    main_window = MainWindow()
    main_window.geometry("450x400")
    main_window.mainloop()

    if __name__ == "__main__":
    main()

    Continue reading...

Compartilhe esta Página