I have been using the John Zelle graphics module for some time now, however this is my first time attempting to use the threading module. I am trying to make multiple objects (circles) that have different starting positions move along my screen simultaneously. This code will also contain recursion and jumping to multiple functions in its final product.
Here is an example of what I am trying to do:
from graphics import *
from random import randint
import time
import threading
class Particle:
def __init__(self):
self.xpos = randint(0,50)
self.ypos = randint(0,50)
self.graphic = Circle(Point(self.xpos,self.ypos),5)
self.graphic.draw(window)
def move(self):
for step in range(5):
self.xpos += 1
self.ypos += 1
self.graphic.move(self.xpos,self.ypos)
time.sleep(0.5)
window = GraphWin("window",500,500)
threading.Thread(target=Particle()).start()
threading.Thread(target=Particle()).start()
After different attempts of trying to use threading, I contnued to get two different errors.
This (from the code above):
Exception in thread Thread-1:
Traceback (most recent call last):
Thread-2 File "/usr/lib/python3.11/threading.py", line 1038, in _bootstrap_inner
:
Traceback (most recent call last):
File "/usr/lib/python3.11/threading.py", line 1038, in _bootstrap_inner
self.run()
File "/usr/lib/python3.11/threading.py", line 975, in run
self._target(*self._args, **self._kwargs)
TypeError: 'Particle' object is not callable
self.run()
File "/usr/lib/python3.11/threading.py", line 975, in run
self._target(*self._args, **self._kwargs)
TypeError: 'Particle' object is not callable
and also:
"RuntimeError: main thread is not in main loop"
I have tried many suggestions from stack overflow and other websites such as:
- Setting my threads to 'daemon = True'
- using 'plt.switch_backend('agg')'
- making a separate thread class
- giving my thread a handle and then using .start on said handle
note: if you are certain that these methods should work please show me how it should be done and I am new to using the thread module.
thanks for any help!
I tried your code,it need some fixes:
Particle.__init__()orParticle().move()as actionparticle1 = Particle()class and then use it's methods liketarget=particle1.move()thread1.join(), main thread will wait till that perticular thread completes it's targeted action (daemon=True or False doesn't matter in this case)Here I am giving you some corrected version of code:
or
or
or
In last snippet, you your window will be opened till your move function completes execution or you close it manually.
If you want to dig deeper in Pytohn Threading, check this guide: https://superfastpython.com/threading-in-python/