如何更改 PyGame 图标?

pythonserver side programmingprogramming更新于 2024/1/5 2:00:00

在构建视频游戏时,我们经常尝试为开发的游戏设置图像或徽标。Python 在 pygame 中提供了一个名为 set_icon() 的函数,可以根据需要设置图标。

Pygame 是一组模块,允许我们开发游戏和多媒体应用程序。这是建立在 SDL(简单直接媒体层)库之上的,该库通过 OpenGL 和 Direct3D 可以低级访问音频键盘、鼠标、操纵杆和图形硬件。

语法

以下是设置游戏图标的语法 -

pygame_icon = pygame.image_load("image_name")
pygame.display.set_icon(pygame_icon)

其中,

  • pygame_icon 是变量的名称。

  • pygame 是库。

  • image_load 是加载图像的函数。

  • image_name 是我们已上传。

  • display.set_icon 是设置所需图标的函数。

要为开发的游戏设置图标,我们必须遵循以下步骤。

  • 首先,我们必须安装 pygame 库

pip install pygame

安装成功后,我们将获得以下输出 –

Collecting pygame
  Downloading pygame-2.3.0-cp39-cp39-win_amd64.whl (10.6 MB)
     ---------------------------------------- 10.6/10.6 MB 4.5 MB/s eta 0:00:00
Installing collected packages: pygame
Successfully installed pygame-2.3.0
Note: you may need to restart the kernel to use updated packages.
  • 现在我们必须初始化 pygame 的图形用户界面 (GUI)。

pygame.init()

上述代码片段的输出如下。

(5, 0)
  • 接下来我们必须通过指定宽度和高度来设置构建的 GUI 游戏的尺寸

size = pygame.display.set_mode([5,5])
print(size)

以下是设置 GUI 游戏尺寸的输出。

<Surface(5x5x32 SW)>
  • 现在将我们想要设置为图标的图像传递给 image.load() 函数。

img = pygame.image.load('image.png')
print(img)

以下是根据我们的要求上传图像的输出。

<Surface(5x5x32 SW)>
  • 接下来我们要将上传的图片传递给 display.set_icon() 函数,这样游戏运行时图片就会被设置在左上角。

pygame.display.set_icon(img)
  • 现在我们要将游戏的运行状态设置为 True。

running = True
  • 现在我们已经设置好了游戏运行时要执行的操作。

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
  • 接下来,我们必须通过将 RGB 颜色传递给 fill() 函数来用指定的颜色填充背景。

size.fill((150,150,0)
  • 现在我们必须更新所做的更改。

pygame.display.update()
  • 最后,我们必须退出 GUI 游戏

pygame.quit()

完整示例

现在让我们立即查看整体代码。

import pygame
pygame.init()
size = pygame.display.set_mode([200,200])
img = pygame.image.load('image.png')
pygame.display.set_icon(img)
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    size.fill((200,200,0))
    pygame.draw.circle(size, (0, 0, 0), (100, 100), 100)
    pygame.display.update()
pygame.quit()

输出

以下是我们在窗口左上角设置的图标的输出。在输出中,我们可以观察到左上角的图标。

示例

让我们看另一个设置 GUI 控制台图标的示例。

import pygame
pygame.init()
size = pygame.display.set_mode([400,200])
img = pygame.image.load('download.jpg')
pygame.display.set_icon(img)
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    size.fill((200,200,0))
    pygame.draw.circle(size, (0, 0, 0), (100, 120), 50)
    pygame.display.update()
pygame.quit()

输出

以下是放置在窗口左上角的图标的输出。


相关文章