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



我有两个多线程,我的目标是使用两个多线程分别打印"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"。

你去吧。我从 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 那里得到的

最新更新