Python3实现的画图及加载图片动画效果示例

  

Python3实现画图与加载图片动画效果

在Python3里,我们可以使用第三方库pygame来实现基本的画图和加载图片动画效果。下面将会给出这一过程的详细攻略。

1. 准备

首先我们需要安装pygame库,可以使用pip来安装,在命令行中输入下面的代码:

pip install pygame

成功安装之后,我们就可以开始使用pygame库。

2. 画图

2.1 创建窗口

在进行画图之前,我们需要先创建一个窗口,来展示我们画出的图形。创建窗口很简单,只需要如下的代码:

import pygame

# 初始化
pygame.init()

# 创建窗口
screen = pygame.display.set_mode((800, 600))

# 设置窗口标题
pygame.display.set_caption("My pygame window")

# 关闭窗口时要做的操作
done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    # 刷新屏幕
    pygame.display.flip()

pygame.quit()

运行这段代码,我们就可以看到创建的空窗口。

2.2 绘制图形

在有了窗口之后,我们就可以开始绘制图形了。例如,我们可以画一个圆形:

import pygame

# 初始化
pygame.init()

# 创建窗口
screen = pygame.display.set_mode((800, 600))

# 设置窗口标题
pygame.display.set_caption("My pygame window")

done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    # 填充屏幕为白色
    screen.fill((255, 255, 255))

    # 绘制圆形
    pygame.draw.circle(screen, (0, 0, 255), (400, 300), 50)

    # 刷新屏幕
    pygame.display.flip()

pygame.quit()

这段代码将在窗口中画出一个蓝色的圆形。

3. 加载图片动画

pygame还可以很方便地加载图片,我们可以将多个图片文件加载进来,然后按一定顺序循环播放,从而实现图片动画效果。

下面给出一个简单的例子,一共有3张图片,按照2秒每帧的速度轮流播放。

import os
import pygame

# 初始化
pygame.init()

# 创建窗口
screen = pygame.display.set_mode((800, 600))

# 设置窗口标题
pygame.display.set_caption("My pygame window")

# 获取当前目录
current_dir = os.path.dirname(__file__)

# 加载图片
images = [
    pygame.image.load(os.path.join(current_dir, 'image1.png')),
    pygame.image.load(os.path.join(current_dir, 'image2.png')),
    pygame.image.load(os.path.join(current_dir, 'image3.png')),
]

# 动画循环变量
animation_index = 0
animation_max_index = len(images) - 1
frame_rate = 2  # 2秒每帧

done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    # 填充屏幕为白色
    screen.fill((255, 255, 255))

    # 显示当前帧图片
    screen.blit(images[animation_index], (300, 200))

    # 计算下一帧的图片
    if animation_index < animation_max_index:
        animation_index += 1
    else:
        animation_index = 0

    # 等待一段时间
    pygame.time.wait(int(1000 / frame_rate))

    # 刷新屏幕
    pygame.display.flip()

pygame.quit()

这段代码我们首先加载了3张图片,然后在主循环里,每隔2秒切换一次图片,从而产生动画效果。

这就是Python3实现画图与加载图片动画的示例说明,更多的使用方法可以参考pygame库的官方文档。

相关文章