Home > OS >  how to make two files run at the same time?
how to make two files run at the same time?

Time:04-03

I have two files, in the first file, there is a function that start an animation of a moving mass attached to a spring. In the second file, there is a function that starts an animated plot. my question is how I can make both animations starts together? note: I can write all the code in one file but still I can't run both functions at the same time, one of the animations has to finish so the other one can start

CodePudding user response:

I think you need https://docs.python.org/3/library/threading.html, it lets you run multiple threads at a time, here is a peice of code I made to make sure it works how I expect it too, mine is just one file but it shouldn't affect the results.

import pygame, threading
pygame.init()
win = pygame.display.set_mode((200, 200))


def animationA():
    height = 10
    vel = 15
    gravity = -1
    while height >= 10:
        win.fill((0, 0, 0), (0, 0, 60, 200))
        height  = vel
        vel  = gravity
        pygame.draw.circle(win, (255, 0, 0), (30, height), 10)
        pygame.display.update()
        pygame.time.delay(1000//30)
def animationB():
    height = 190
    vel = -15
    gravity = 1
    while height <= 190:
        win.fill((0, 0, 0), (140, 0, 60, 200))
        height  = vel
        vel  = gravity
        pygame.draw.circle(win, (0, 0, 255), (170, height), 10)
        pygame.display.update()
        pygame.time.delay(1000//30)
threadA = threading.Thread(target = animationA)
threadB = threading.Thread(target = animationB)

threadA.start()
threadB.start()

Hope this does what you need.

  • Related