为什么我的 pygame 显示在等待输入时没有响应?
- 2025-03-04 08:27:00
- admin 原创
- 39
问题描述:
我尝试使用 python 来显示图像:
import pygame
win = pygame.display.set_mode((500, 500))
DisplayImage("Prologue.jpg", win)
运行时,什么也没有发生。
DisplayImage("Streets.jpg", win)
然而,当我稍后在代码中尝试完全相同的操作时,它运行得非常完美。
我检查了一下,图片和.py文件在同一个文件夹里,而且我没有打错名字。
该功能为:
def DisplayImage(imageName, screen):
screen.fill((0, 0, 0))
Image = pygame.image.load(imageName).convert()
screen_rect = screen.get_rect()
Image_rect = Image.get_rect().fit(screen_rect)
Image = pygame.transform.scale(Image, Image_rect.size)
screen.blit(Image, [0, 0])
pygame.display.update()
更新:我注释掉了所有行,并复制并粘贴了该行,因此它是唯一可以运行的行。它运行完美。
更新 2:找到问题。它不起作用的原因是 pygame 窗口“没有响应”。我不知道是什么原因导致它没有响应,但在一次测试运行中,我没有让它显示“没有响应”,图像加载正常。当我输入我的玩家名称时,总是会出现“没有响应”,函数如下所示:
def createName():
playerName = input("Enter the player name
")
desiredName = input("Is "+playerName+" the desired name?[1]Yes/[2]No
")
if desiredName == "1":
return playerName
elif desiredName == "2":
playerName = createName()
有时候我输入玩家名字时什么都没发生,过一会儿字母才会显示出来。如果发生这种情况,pygame 窗口肯定没有响应。
解决方案 1:
您不能input
在应用程序循环中使用。input
等待输入。当系统等待输入时,应用程序循环将停止,游戏将不会响应。
使用KEYDOWN
事件代替input
:
run = True
while run:
event_list = pygame.event.get()
for event in event_list:
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if pygame.key == pygame.K_1:
# [...]
if pygame.key == pygame.K_2:
# [...]
另一种选择是在单独的线程中获取输入。
最小示例:
import pygame
import threading
pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
color = "red"
def get_input():
global color
color = input('enter color (e.g. blue): ')
input_thread = threading.Thread(target=get_input)
input_thread.start()
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window_center = window.get_rect().center
window.fill(0)
pygame.draw.circle(window, color, window_center, 100)
pygame.display.flip()
pygame.quit()
exit()
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD