首页 > 解决方案 > Python PyGame 图像(大金刚)不动

问题描述

我制作了一个简单的 pygame,它应该用箭头键左右移动驴图像。驴图像在文件夹中并且已经出现,但它不会左右移动。如果有帮助,我在 python 3.7 上。

我已经找了半个多小时,但我不明白为什么它不起作用,请帮忙。

这是我的代码:

import pygame
from pygame.locals import*
charx = 1
chary = 1
vel = 10
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("Pygame")
char = pygame.transform.scale(pygame.image.load('donkey.jpg'), (128, 128))

keys = pygame.key.get_pressed()
clock = pygame.time.Clock()
run = True
while run:
    clock.tick(10)

    if keys[pygame.K_LEFT]:
        charx = charx - vel
    elif keys[pygame.K_RIGHT]:
        charx = charx + vel
    else:
        run = False
    run = True

    win.blit(char,(charx, chary))
    pygame.display.update()

当我运行程序时,窗口出现,左上角有大金刚。但他没有用箭头键移动。

标签: pythonpython-3.xpygame

解决方案


我不确定为什么,但如果你添加事件循环它就可以了。
您还需要在循环keys = pygame.key.get_pressed()内移动线。while

while run:
    #add the following 3 lines, to check over events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        charx = charx - vel
    elif keys[pygame.K_RIGHT]:
        charx = charx + vel
    else:
        run = False
    run = True

    win.blit(char,(charx, chary))
    pygame.display.update()
    clock.tick(10)

我只能猜测pygame.key.get_pressed()如果pygame.event.get()不在主循环中消耗它就不能正常工作。


推荐阅读