Reputation: 1
So: I try to add Error-Masseges to my code. Each of those i want to display in a separate tkinter Toplevel window. So far so good.
But for this i need to pause my code after the Error-Window was created and wait until the user presses the "okay" button in the Error-Window to continue. Only then the code is allowed to go on.
The creation of the Error-Window i have problems with is within the mainloop of another tkinter window. Latter can not be destroyed without huge problems. Does anyone have a solution for me? Am i maybe committing a sin against the python-god? Can i pause a mainloop?
I tried wait_window(win) (btw: what does it do? It doesn't seem to work as i understood it. Isn't it supposed to be waiting for the given window to be destroyed?)
Also wait() didn't work for me.
My coding senses tell me it has something to do with the mainloop within a mainloop. The code regarding is unfortunately way to long to post it here and a recreation with a sample would be a huge trouble. I hope my description is specific enough.
I also tried to research, but for some reason noone seems to have the exact same problem. There are similar but no solution helped me.
If a sample is REALLY needed please, let me know or downvote my question then i will try to make the core problem as short as possible.
Upvotes: -2
Views: 67
Reputation: 386010
First, you shouldn't be calling mainloop
more than once. Also, you shouldn't create more than one instance of Tk
. It's not clear if you're doing that or not.
To wait until a window is destroyed you can use the wait_window
method. If you're creating an error dialog, you also probably want to do a grab. That means you want all events to funnel into that widget so that the user can't interact with other widgets until they acknowledge the dialog.
To do a grab, call the grab_set
method. The grab will automatically be released when the window is destroyed.
The following example illustrates this technique. Notice that you can click the button in the main window only if the dialog isn't shown. Once the dialog has been shown, the function that creates it won't return until the dialog window has been destroyed.
When you create a window in this way, the dialog is considered to be a modal dialog. ie: it enters a mode where nothing else happens until the window is destroyed.
import tkinter as tk
def show_error(message="Danger Will Robinson!"):
toplevel = tk.Toplevel(root)
message = tk.Label(toplevel, text=message, bd=2, relief="groove")
button = tk.Button(toplevel, text="Ok", command=toplevel.destroy)
button.pack(side="bottom")
message.pack(side="top", fill="both", expand=True, ipadx=10, ipady=10, padx=10, pady=10)
print("waiting for window to be destroyed...")
toplevel.grab_set()
toplevel.wait_window()
print("done waiting")
root = tk.Tk()
button = tk.Button(text="Click me", command=show_error)
button.pack(padx=20, pady=20)
tk.mainloop()
Upvotes: 0