Python Forum
keep gui open if I use "quit"
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
keep gui open if I use "quit"
#1
Hi,

I have code with a gui...

I'm using "quit" to end the execution of my code if something occurs...

Using "quit" the gui closes too...

Is there a way to get the gui stay open, if I use "quit" in my code?

I'm totally new to this problem...

Thanks a lot for your help!!
Reply
#2
(Aug-21-2023, 08:43 PM)flash77 Wrote: Is there a way to get the gui stay open, if I use "quit" in my code?
Why are you using "quit" if you want the GUI to stay open?
menator01 likes this post
Reply
#3
quit() just raises an exception. You can catch the exception before it exits the GUI.
import tkinter as tk


def do_something():
    print("I quit()!")
    quit()


def button_cb():
    try:
        do_something()
    except SystemExit:
        print("Ha, ha!")


root = tk.Tk()
tk.Button(root, text="Push me", command=button_cb).pack(padx=100, pady=100)
root.mainloop()
If you are writing all the code, I think you'd do better making your own special quit exception and having your scripts raise that if they need to exit. The convention is that exit() will exit your program. Following conventions is important for code maintenance. You want to write code that is easy for other people to understand.
import tkinter as tk


class ExitScriptException(Exception):
    """Exception for exiting a script"""


def script():
    print("I'm doing something.")
    raise ExitScriptException("I finished.")
    print("This code will never be reached")


def run_script(script):
    try:
        script()
    except ExitScriptException as msg:
        # Only catch ExitScript exceptions.  Let others close down the program.
        print(msg)


root = tk.Tk()
tk.Button(root, text="Push me", command=lambda: run_script(script)).pack(
    padx=100, pady=100
)
root.mainloop()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Error message box and quit app Kumarkv 1 2,288 May-19-2020, 07:05 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020