Search code examples
pythontkintercustomtkinter

invalid command name "1775568714624update" in customtkinter


**when I trying to make more than one interface in customtkinter lib, I face Error like that given below and my program stuck, I have never face this problem in normal tkinter **

invalid command name "1775568714624update" while executing "1775568714624update" ("after" script) invalid command name "1775530397696check_dpi_scaling" while executing "1775530397696check_dpi_scaling" ("after" script) invalid command name "1775587007232_click_animation" while executing "1775587007232_click_animation" ("after" script)

from customtkinter import (CTk, CTkButton)

def fun():
    root.destroy()
    inp = CTk()
    inp.mainloop()

root = CTk()
root.geometry('250x250')
but = CTkButton(master=root, width=50, height=25,text="TEST" ,command=fun).pack(expand=True) 
   
root.mainloop()

Solution

  • This is a very bad practice. As a general rule of thumb you should never create more than one instance of a root window, or call mainloop more than once.

    In this specific case, customtkinter uses the after command to handle the animation of the button. However, in between the button being pressed and released you're destroying the root window. That makes it impossible for the after command to run since it has been destroyed.

    If you want to be able to destroy and recreate root windows, the better solution is to put your entire UI in a frame, and then destroy and replace that frame while keeping the root window intact.

    It might look something like this:

    from customtkinter import (CTk, CTkButton, CTkFrame)
    
    def fun():
        global f
        f.destroy()
        f = CTkFrame(master=root)
    
    root = CTk()
    root.geometry('250x250')
    f = CTkFrame(master=root)
    f.pack(fill="both", expand=True)
    but = CTkButton(master=f, width=50, height=25,text="TEST" ,command=fun).pack(expand=True)
    
    root.mainloop()
    

    Though, it's best to move the creation of your UI into a function or class definition.