python - 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()
当我运行程序时,窗口出现,左上角有大金刚。但他没有用箭头键移动。
解决方案
我不确定为什么,但如果你添加事件循环它就可以了。
您还需要在循环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()
不在主循环中消耗它就不能正常工作。
推荐阅读
- python - 使用 python-docx 阅读口音
- actionscript-3 - as3 - tweenlite X 坐标接近并变慢
- python - Python:if elif 循环
- javascript - 需要JS处理的html页面如何下载和查询?
- php - 如果其他 2 个字段相同,如何添加列
- python - XGBoost 包无法在 PyCharm 中加载
- plugins - can't change ImageSource of the plugin of daniel-luberda/DLToolkit.Forms.Controls
- xforms - ODK XForms format-date Hour and Minute 输出为 0000
- javascript - Firebase js库从非空数据库中检索空数据
- sql - 赞成票和反对票的数据库