pythontkinter

Set button command to None but no effect in python tkinter


I want to remove button's click event when click it, but this code has no effect. Every button popup msgbox again and again:

from tkinter import *
from tkinter import messagebox

root = Tk()
root.geometry("500x500+400+200")

def show_btn(b):
    messagebox.showinfo(message=f"{b.cget('text')}")
    b.config(command=None)

for x in range(3):
    btn = Button(root, text=f"{x}")
    btn.config(command=lambda b=btn: show_btn(b))
    btn.pack()

root.mainloop()

Solution

  • How about

    b.config(state="disable")
    

    to disable button.

    It will be also grayed.


    And later you can activate it again

    b.config(state="normal")
    

    from tkinter import *
    from tkinter import messagebox
    
    root = Tk()
    root.geometry("500x500+400+200")
    
    def show_btn(b):
        messagebox.showinfo(message=f"{b.cget('text')}")
        b.config(state="disable")
        #b["state"] = "disable"
    
    def activate():
        for btn in all_buttons:
            btn.config(state="normal")
            #btn["state"] = "normal"
    
    all_buttons = []
    
    for x in range(3):
        btn = Button(root, text=f"{x}")
        btn.config(command=lambda b=btn: show_btn(b))
        btn.pack()
        all_buttons.append(btn)
    
    Button(root, text="Activate Again", command=activate).pack()
    
    root.mainloop()