多个线程永远无法运行,也无法获取事件

时间:2019-08-15 01:37:15

标签: python multithreading pygame

我有两个多线程,我的目标是使用两个多线程分别打印“ mouse1”和“ mouse2”。但是该程序无法正常工作。它什么也不打印,也无法正确关闭。

import threading
import pygame

screen = pygame.display.set_mode((800, 800))
def mouse1():
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                print('mouse1')
            else:
                pass

def mouse2():
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                print('mouse2')
            else:
                pass

t2 = threading.Thread(target=mouse1)
t1 = threading.Thread(target=mouse2)

t1.start()
t2.start()

t1.join()
t2.join()

我希望当单击鼠标按钮时,输出会很多“ mouse1”和“ mouse2”。

1 个答案:

答案 0 :(得分:-1)

您在这里。我从https://www.pygame.org/docs/tut/PygameIntro.html复制了示例,然后跟随https://stackoverflow.com/a/34288442/326242来区分按钮。

import sys, pygame
pygame.init()

LEFT_MOUSE_BUTTON = 1
MIDDLE_MOUSE_BUTTON = 2
RIGHT_MOUSE_BUTTON = 3

def handleMouseEvents(event):
    if event.type == pygame.MOUSEBUTTONDOWN:
        if event.button == LEFT_MOUSE_BUTTON:
            print("Left mouse button clicked!")
        elif event.button == MIDDLE_MOUSE_BUTTON:
            print("Middle mouse button clicked!")
        elif event.button == RIGHT_MOUSE_BUTTON:
            print("Right mouse button clicked!")

        sys.stdout.flush()
    else:
        pass

size = width, height = 320, 240
speed = [2, 2]
black = 0, 0, 0

screen = pygame.display.set_mode(size)

ball = pygame.image.load("intro_ball.gif")
ballrect = ball.get_rect()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        else:
            handleMouseEvents(event)

    ballrect = ballrect.move(speed)
    if ballrect.left < 0 or ballrect.right > width:
        speed[0] = -speed[0]
    if ballrect.top < 0 or ballrect.bottom > height:
        speed[1] = -speed[1]

    screen.fill(black)
    screen.blit(ball, ballrect)
    pygame.display.flip()

我修复的主要问题是:

  • 在打印到输出后,添加了对sys.stdout.flush()的调用。否则,直到程序结束并自动刷新输出后,您才能看到输出。
  • 添加了示例代码,该代码实际上设置了显示区域并在其上显示内容。
  • 选中event.button,查看单击了哪个按钮。
  • 摆脱了线程问题。 Pygame有自己的线程系统,除非您真的知道自己在做什么,否则请遵循它。

您需要在源代码中添加intro_ball.gif以及该代码所在的文件。我是从https://www.pygame.org/docs/_images/intro_ball.gif那里获得的