简体   繁体   中英

Python - How to run two loops at the same time?

So simply put I want different objects to have their own tick loop code running independently of each other (As in one tick loop does not stop all other tick loops in my app).

I've created a basic module that has a class for shapes and the main body for spawning them however the tick loop of the class holds up the main parts loop.

I have even tried splitting the code into two modules to see if that would work but that still ran the two loops separately.

Here is my code:

(main code)

from random import *
from tkinter import *
from time import *

import RdmCirClass

size = 500
window = Tk()
count = 0
d = 0
shapes = []

canv = Canvas(window, width=size, height=size)
canv.pack()
window.update()
while True:
    col = choice(['#EAEA00'])
    x0 = randint(0, size)
    y0 = randint(0, size)
    #d = randint(0, size/5)
    d = (d + 0.01)
    outline = 'white'
    shapes.append(1)
    shapes[count] = RdmCirClass.Shape("shape" + str(count), canv, col, x0, y0, d, outline)
    shapes[count].spawn()
    count = count+1

    print("Circle Count: ",count)
    window.update()

(Shape Class)

from random import *
from tkinter import *
from time import *   

class Shape(object):
    def __init__(self,name, canv, col, x, y,d,outline):
        self.name = name
        self.canv = canv
        self.col = col
        self.x = x
        self.y = y
        self.d = d
        self.outline = outline
        self.age=0
        self.born = time()

    def death(self):
        pass

    def tick(self):
        self.age = time() - self.born

    def spawn(self):
        self.canv.create_oval(self.x, self.y, self.x + self.d, self.y + self.d, outline=self.outline, fill = self.col)
        while True:
            self.tick() 

Roughly speaking, there are three ways to accomplish what you want. Which is best depends greatly on what exactly you're trying to do with each independent unit, and what performance constraints and requirements you have.

The first solution is to have an independent loop that simply calls the tick() method of each object on each iteration. Conceptually this is perhaps the simplest to implement.

The other two solutions involve multiple threads, or multiple processes. These solutions come with sometimes considerably complexity, but the benefit is that you get the OS to schedule the running of the tick() method for each object.

我不明白您的代码在做什么,但是我的建议是使用线程: https : //pymotw.com/2/threading/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM