Python Closing Toplevel Window Error

122 views Asked by At

I wanted this code to create a popup error window that destroys itself after 4 seconds but can also be closed via a button.

def error(self):
    top = Toplevel()
    top.after(4000, lambda: top.destroy())
    center_window(300,100, top)
    top.title("Error")
    Label(top, text="Please enter a valid code", height=3, width=200).pack()
    ok = Button(top, text="OK", command=top.destroy)
    ok.pack()
    ok.bind("<Return>", lambda a: top.destroy())
    ok.focus_set()

I have run the code and it works fine 90% of the time except sometimes it throws this error:

 TypeError: <lambda>() takes exactly 1 argument (0 given)

I have done research that says it is Tkinters threading. I am not sure if this is my issue but when I take out this line of code:

top.after(4000, lambda: top.destroy())

It seems to work. If anyone could help me, I have taught myself what I know of python, so I am sure there are holes in my learning. I think I may need to somehow use the main thread of execution to destroy this window, or otherwise create my own custom widget. Any help is appreciated.

2

There are 2 answers

0
Temsia Carrolla On

When using after or bind, you don't need to use lambda. Instead, for example, use:

top.after(4000, top.destroy)

which references the function top.destroy directly.

0
Reblochon Masque On

You can directly bind the function to be called instead of using a lambda:

    top.after(4000, top.destroy)
...
    ok.bind("<Return>", top.destroy)

You would use a lambda, for instance, if you needed to pass arguments to the function; this is not the case here.