首页 > 解决方案 > 为什么pygame队列不响应它在线程中的迭代?

问题描述

你好。开门见山。我有线程 python 模块的问题。当我创建一个从 Thread 类继承的类时,我认为我的程序正在从一个重载的事件队列中崩溃,即使我正在run线程方法中遍历所有这些队列。但如果我通过pygame.event.get()主线程,一切正常。例如我写了一个简单的“游戏”。

有用:

import pygame
import threading as tg
import sys

screen = pygame.display.set_mode((300, 300))
screen.fill((155, 155, 155))
ball = pygame.Surface((10, 10))
ball.fill((100, 200, 100))
x = 80
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            x += 1

    screen.blit(ball, (x, 40))
    pygame.display.flip()

不工作:

import pygame
import threading as tg
import sys

class SimpleThread(tg.Thread):
    def __init__(self, x):
        tg.Thread.__init__(self)
        self.run1 = True
        self.x = x

    def run(self):
        while self.run:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.run1 = False
                    break
                if event.type == pygame.MOUSEBUTTONDOWN:
                    self.x += 1


screen = pygame.display.set_mode((300, 300))
screen.fill((155, 155, 155))
ball = pygame.Surface((10, 10))
ball.fill((100, 200, 100))
x = 80

th = SimpleThread(x)
th.start()
while th.run:      
    screen.blit(ball, (th.x, 40))
    pygame.display.flip()

pygame.quit()
sys.exit()

在我看来,它应该以相同的方式工作,但事实并非如此。

我认为这与线程中的命名空间有关,但希望您能帮助我理解这个问题。感谢您阅读此内容:o

标签: pythonmultithreadingpygame

解决方案


推荐阅读