PyGame 如何更改图标

PyGame 如何更改图标

在构建视频游戏时,我们经常尝试为该开发的游戏设置图像或标志。Python提供了一个名为set_icon()的函数,用于设置所需的图标。

Pygame是一组模块,允许我们开发游戏和多媒体应用程序。它构建在SDL(Simple Direct Media Layer)库的基础上,通过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()
  • 最后我们不得不放弃图形界面游戏
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()

输出

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

PyGame 如何更改图标

示例

让我们来看另一个例子,设置图标在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()

输出

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

PyGame 如何更改图标

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程