目录
代码段
import sys
import pygame
pygame.init()
# 使用pygame之前必须初始化
LENGTH = 1000 # 主屏窗口长度
WIDTH = 680 # 主屏窗口宽度
screen = pygame.display.set_mode((LENGTH,WIDTH)) # 设置主屏窗口
# 说明:set_mode()可以短时间显示主屏窗口
pygame.display.set_caption("图片移动测试") # 设置窗口标题
# 说明:若不设置窗口标题,则窗口标题默认为“pygame window”
img = pygame.image.load("t02_img.png") # 加载本地图片
rect = img.get_rect() # 获取图片区域
rect.x = 500 # 设置显示位置
rect.y = 340 # 设置显示位置
def move(rect,direction): # 图片移动函数
# 说明:图片移动实质是改变rect.top或rect.left,并确保图片不会移出主屏窗口
speed = 20 # 移动速度
if rect.top-speed>=0 and direction == 'U': # 上
rect.top -= speed
elif rect.top+rect.height+speed<=WIDTH and direction == 'D': # 下
rect.top += speed
elif rect.left-speed>=0 and direction == 'L': # 左
rect.left -= speed
elif rect.left+rect.width+speed<=LENGTH and direction == 'R': # 右
rect.left += speed
while True:
# 说明:while True循环可以使得主屏窗口得以保留
screen.fill((0, 0, 0)) # 填充
# 说明:在更新之前填充可以覆盖之前的图片,防止图片移动后出现重影
screen.blit(img, rect) # 传送
# 说明:给主屏窗口传送移动后的图片区域
pygame.display.update() # 更新
# 说明:更新屏幕显示,给用户一种图片发生移动的视觉效果
for event in pygame.event.get(): # 循环获取事件并监听事件状态
if event.type == pygame.KEYDOWN: # 按下了按键
if event.key == pygame.K_UP: # 上
move(rect,'U')
elif event.key == pygame.K_DOWN: # 下
move(rect,'D')
elif event.key == pygame.K_LEFT: # 左
move(rect,'L')
elif event.key == pygame.K_RIGHT: # 右
move(rect,'R')
if event.type == pygame.QUIT: # 点击了关闭按钮
pygame.quit() # 卸载模块
sys.exit() # 退出程序
效果展示
备注:图片为170*174像素
pygame图片移动测试 20230107