Search code examples
pythonuser-interfacetkintermessageboxtkmessagebox

Command execution on closing "X" Tkinter MessageBox


I am trying to restart my main GUI/Halt the program flow when I Click on the "X" button in my tkinter messagebox . Any idea how can I do this ?

PS: I have read the many threads about closing the main GUI itself but nothing specific to messagebox

By default , my code proceeds to ask me for an output path using the filedailog.askdirectory() method when clicking "ok", or on closing the messagebox

My message box and the main GUI in the background


Solution

  • There's no simple way to add a custom handler to the "X" button. I think it's better to use messagebox.askokcancel() variation of messageboxes instead of showinfo, and halt the program if the returned result is False:

    import tkinter as tk
    from tkinter import messagebox, filedialog
    
    root = tk.Tk()
    
    
    def show_messagebox():
        result = messagebox.askokcancel("Output path", "Please select an output file path")
        if result:
            filedialog.askdirectory()
        else:
            messagebox.showinfo("Program is halted")
    
    
    tk.Button(root, text="Show messagebox", command=show_messagebox).pack()
    
    root.mainloop()
    

    Or, even simpler, you can just show filedialog.askdirectory() directly. If the user doesn't want to choose directory, they can click on the "Cancel" button, and then the program checks if there was empty value returned, and halts if so:

    import tkinter as tk
    from tkinter import messagebox, filedialog
    
    root = tk.Tk()
    
    
    def show_askdirectory():
        directory = filedialog.askdirectory(title="Please select an output file path")
        if not directory:
            messagebox.showinfo(message="The program is halted")
        else:
            messagebox.showinfo(message="Chosen directory: " + directory)
    
    
    tk.Button(root, text="Choose directory", command=show_askdirectory).pack()
    
    root.mainloop()