python - 为什么我的显示器在等待输入时没有响应?
问题描述
我尝试使用 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\n")
desiredName = input("Is "+playerName+" the desired name?[1]Yes/[2]No\n")
if desiredName == "1":
return playerName
elif desiredName == "2":
playerName = createName()
有时,当我输入玩家名称时,什么也没有发生,而且这些字母会在一段时间后出现。如果发生这种情况,pygame 窗口必然不会响应。
解决方案
您不能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()
推荐阅读
- awk - 将参数列表作为从另一个制表符分隔的文件中提取的文件名
- android - 在没有第三方库的情况下,可以通过 React-Native 访问哪些硬件/传感器?
- ios - Swift CollectionView 获取第一个单元格
- eclipse - 安装 Eclipse Neon 错误
- python - 如何在 Jupyter 笔记本中显示蛋白质数据库 PDB?
- python - 如何根据python中的日期(mm-dd-yy中的形式)从数据集中选择行?
- php - php中字符串内的单双引号问题
- ios - Swift,iOS:如何从我的 firebase 数据库中提取数据?
- r - 递归特征消除和变量选择
- c++ - 附加深度纹理 (C++) 时 OpenGL FBO 纹理混乱