首页 > 解决方案 > 为什么我的显示器在等待输入时没有响应?

问题描述

我尝试使用 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 窗口必然不会响应。

标签: pythonpygame

解决方案


您不能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()

推荐阅读