为什么我的显示器在等待输入时没有响应?

2024-10-03 17:20:40 发布

您现在位置: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窗口肯定不会响应


Tags: rect图像image名称键入defdisplayscreen
1条回答
网友
1楼 · 发布于 2024-10-03 17:20:40

不能在应用程序循环中使用inputinput等待输入。当系统等待输入时,应用程序循环将停止,游戏将不响应

使用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()

相关问题 更多 >