Why I can't exit code in python?

298 views Asked by At

I've tried use exit(), exit(0), sys.exit()(I've import sys) and quit(), but none of them can help me to exit code.

Here is my code when using exit():

from pystray import MenuItem as item
import pystray
from PIL import Image


while True:
    def show():
        exit()
    image = Image.open("TrayIcon.jpg")
    menu = (item('exit', show),)
    icon = pystray.Icon("name", image, "title", menu)
    icon.run()
    print('running...')

This is the error when using exit()

An error occurred when calling message handler
Traceback (most recent call last):
  File "D:\py3.7\lib\site-packages\pystray\_win32.py", line 402, in _dispatcher
    uMsg, lambda w, l: 0)(wParam, lParam) or 0)
  File "D:\py3.7\lib\site-packages\pystray\_win32.py", line 213, in _on_notify
    descriptors[index - 1](self)
  File "D:\py3.7\lib\site-packages\pystray\_base.py", line 324, in inner
    callback(self)
  File "D:\py3.7\lib\site-packages\pystray\_base.py", line 449, in __call__
    return self._action(icon, self)
  File "D:\py3.7\lib\site-packages\pystray\_base.py", line 544, in wrapper0
    return action()
  File "C:/Users/admin/AppData/Roaming/JetBrains/PyCharmCE2022.1/scratches/scratch.py", line 9, in show
    exit()
  File "D:\py3.7\lib\_sitebuiltins.py", line 26, in __call__
    raise SystemExit(code)
SystemExit: None

i aslo have tried to turn

from pystray import MenuItem as item
import pystray
from PIL import Image


def show():
    icon.stop()


image = Image.open("TrayIcon.jpg")
menu = (item('exit', show),)
icon = pystray.Icon("name", image, "title", menu)
icon.run()

while True:
    print('running...')

At this time, i can't running... is not show when the icon is in the tray, i must exit it to show.

Other errors are quiet similar with the error when using exit()

2

There are 2 answers

12
Mohamad Ghaith Alzin On

I've given this a test now and you don't need to call exit(). Instead, call icon.stop()

Also, no need for the infinite loop!

from pystray import MenuItem as item
import pystray
from PIL import Image

def show():
    icon.stop()
    
image = Image.open("TrayIcon.jpg")
menu = (item('exit', show),)
icon = pystray.Icon("name", image, "title", menu)
icon.run()

Note: the following link would be useful for you as well

https://github.com/moses-palmer/pystray/issues/17

Pystray systray icon

5
Gajera Yugantkumar Rajanikumar On

To exit the shell and return to the system prompt, type exit() or Ctrl-D.