Search code examples
pythonpython-3.xmultithreadingruntime-errorpystray

RuntimeError: can't create new thread at interpreter shutdown. Python 3.12


I am making a mouse jiggler and I can't get acces to the tray icon once the loop in the script is launched. I have asked another question but no one has answered yet, so I kept digging deeper into the topic in order to resolve my issue. So, I found a solution as I assumed it would be - threads. I kinda understand the code I found, but not entirely, so maybe now the issue is about my understanding and not the code itself.

I found the same questions with the same error published not long ago but there were no answers. So, I might presume there is a bug with threading.py in Python 3.12 - I dunno.

Here's my code:

from PIL import Image
import pyautogui
import time
import pystray
import threading
import os

class MyClass:
    def __init__(self):
        self.__running = False
        self.__stop_event = threading.Event()
        
    def run(self):
        while not self.__stop_event.is_set():
            pyautogui.moveRel(50, 0, duration = 0)
            pyautogui.moveRel(-50,0, duration = 0)
            time.sleep(5)
            print("running")
                
    def change_running_state(self):
        print(f"Running: {self.__running}")
        self.__running = not self.__running
        print(f"Running: {self.__running}")
        
        if self.__running:
            self.__stop_event.clear()
            t = threading.Thread(target=self.run)
            t.start()
        else:
            self.__stop_event.set()
if __name__ == "__main__":
    def start(icon, item):
            print("start")
            cl.change_running_state()

    def stop(icon, item):
        print("stop")
        cl.change_running_state()

    def exit_program(icon, item):
        print("exit")
        cl.change_running_state()
        icon.stop()
        os._exit(1)

image = Image.open("macos.jpg")

cl = MyClass()
icon = pystray.Icon("macos", image)
icon.menu=pystray.Menu(
    pystray.MenuItem("Start", start),
    pystray.MenuItem("Stop", stop),
    pystray.MenuItem("Exit", exit_program),
)
icon.run_detached()

The tray icon works and menu items appear there whenever I click on the icon now. And menu items should have worked, I thought, too. Instead, I get the following:

start
Running: False
Running: True
An error occurred when calling message handler
Traceback (most recent call last):
  File "C:\Users\derby\AppData\Local\Programs\Python\Python312\Lib\site-packages\pystray\_win32.py", line 412, in _dispatcher
    return int(icon._message_handlers.get(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\derby\AppData\Local\Programs\Python\Python312\Lib\site-packages\pystray\_win32.py", line 224, in _on_notify 
    descriptors[index - 1](self)
  File "C:\Users\derby\AppData\Local\Programs\Python\Python312\Lib\site-packages\pystray\_base.py", line 328, in inner       
    callback(self)
  File "C:\Users\derby\AppData\Local\Programs\Python\Python312\Lib\site-packages\pystray\_base.py", line 453, in __call__
    return self._action(icon, self)
           ^^^^^^^^^^^^^^^^^^^^^^^^
  File "c:\Users\derby\PythonWorkspace\Mouse Jiggler\Jiggler copy.py", line 34, in start
    cl.change_running_state()
  File "c:\Users\derby\PythonWorkspace\Mouse Jiggler\Jiggler copy.py", line 28, in change_running_state
    t.start()
  File "C:\Users\derby\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 971, in start
    _start_new_thread(self._bootstrap, ())
RuntimeError: can't create new thread at interpreter shutdown

So what's going on here? I might surely be tired after 6 hours coding, but still it is hard for me, novice programmer, to understand that by myself.


Solution

  • The solution is to use Python version under 3.12. Now I use 3.11.7. The code works perfectly fine.