Search code examples
pythonuser-interfacetkintermessagebox

How can I force a window to close when a message box (e.g. an error message) appears/opens?


So I have a button in my code that does two things: it starts a process which takes a while, and it also opens a window with a progress bar that works until the other process finishes, then it closes. I want to make it so it (the window with the progress bar) will also close if a message box appears. That way if the long process gets screwed up, the progress bar won't run forever. A snippet of my code is below (everything else not shown works the way I want it to):

def progress_bar():
    info_window = Toplevel(main_window)
    info_window.title("Progress_Bar")
    info_window.geometry("200x50")
    progress = Progressbar(info_window, orient=HORIZONTAL, length=200, mode='indeterminate')
    label3 = Label(info_window, text="Loading...")
    label3.pack() 
    while true != "True":
        progress.pack()
        progress['value'] += 1
        info_window.update_idletasks()
        time.sleep(0.01)
    if progress['value'] == 100:
        progress['value'] = 0
    if true == "True":
        info_window.destroy()
    if show_error_message() == True:   # <-- This is where I'm unsure; this statement
        info_window.destroy()          # Obviously doesn't work but I don't know
                                       # exactly how to phrase it correctly to make it work
def show_error_message():
    messagebox.showerror("ERROR 4343", "KILLIN' IT")  # <-- this occurs when I press a different button 
                                                      

so the basic idea: progress bar window opens at the push of one button and runs until the error message occurs at the push of another button.


Solution

  • Maybe what you can do is, after the error is shown, call a function that closes the window:

    def closewindow():
        #do something like saving before closure
        info_window.destroy()
        self.root.destroy() #if you also want to close the main window
    
    def show_error_message():
        messagebox.showerror("ERROR 4343", "KILLIN' IT") 
        closewindow()