-1

From what I understand, using sys.exit is not compatible with PyCharm and other IDEs, yet other exit methods that don't do garbage collection are not recommended. If I'm developing in PyCharm how can I properly shut down the program?

In the below example I am attempting to use a hot key to exit the program, yet the test statement is never reached. Is this an incorrect syntax or related to using the wrong exit command?

#Import modules
from tkinter import * #For images
from PIL import Image, ImageTk #For images
import os #For working directory
from pynput import keyboard #For hotkeys
#Set default directory
os.chdir('C:\\Users\\UserName\\Desktop\\Python\\SomeFolderName')

#Display Menu
root = Tk()
image = Image.open('menu.png')
display = ImageTk.PhotoImage(image)
root.overrideredirect(True) #Remove toolbar
label = Label(root, image=display)
label.pack()
root.mainloop()

#Functions
def ExitProgram():
print('test')
sys.exit(0)

#Define hotkeys
with keyboard.GlobalHotKeys({
'<ctrl>+w': ExitProgram,
'<ctrl>+0': ExitProgram}) as h:
h.join()

4 Answers4

1

Use the quit() function to exit the program. This is a built-in function from Python in order to exit the program.

Happy Coding!

Dharman
  • 30,962
  • 25
  • 85
  • 135
Srishruthik Alle
  • 500
  • 3
  • 14
0

This answer from a similar question might be a useful answer for you.

Python exit commands - why so many and when should each be used?

I actually use VS code and sys.exit(0) is fine, but can also use quit() which is also fine.

D.L
  • 4,339
  • 5
  • 22
  • 45
0

Use quit() or exit() to terminate your program. quit() and exit() are synonymous and do the exact same thing.

In addition to calling sys.exit(), using quit() does some other internal cleanup, such as closing input streams.

They are briefly discussed in the official documentation here: https://docs.python.org/3/library/constants.html#quit

The Matt
  • 1,423
  • 1
  • 12
  • 22
0

Nothing past root.mainloop() will execute because it never returns. Move the with keyboard... code before root.mainloop().

Glenn Gribble
  • 390
  • 1
  • 7
  • Thank you so much. I've been trying to figure this out for hours. –  Dec 24 '20 at 02:03
  • Actually I did that and am getting "ExitProgram" not defined when the with keyboard code is above the function declarations. –  Dec 24 '20 at 02:06
  • Yes. Move that before, too. `root.mainloop()` should be the last line. – Glenn Gribble Dec 24 '20 at 04:11