我有两个多线程,我的目标是使用两个多线程分别打印“ 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”。
答案 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()
我修复的主要问题是:
event.button
,查看单击了哪个按钮。您需要在源代码中添加intro_ball.gif
以及该代码所在的文件。我是从https://www.pygame.org/docs/_images/intro_ball.gif那里获得的