See pygame.display.set_icon()
:
[...] Some systems do not allow the window icon to change after it has been shown. This function can be called before pygame.display.set_mode()
to create the icon before the display mode is set.
Set the icon before pygame.display.set_mode((1600, 900))
:
icon = pygame.image.load('reindeer.png')
pygame.display.set_icon(icon)
screen = pygame.display.set_mode((1600, 900))
pygame.display.set_caption(‘Elizabeth2’)
In addition, the size of the icon is limited:
[...] You can pass any surface, but most systems want a smaller image around 32x32.
If the icon is not displayed, try a smaller icon.
Make sure that the resource (image) path and the working directory is correct.
The image file path has to be relative to the current working directory. The working directory is possibly different to the directory of the python file.
The name and path of the file can be get by __file__
. The current working directory can be get by os.getcwd()
and can be changed by os.chdir(path)
.
import os
sourceFileDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(sourceFileDir)
An alternative solution is to find the absolute path.
If the image is relative to the folder of the python file (or even in the same folder), then you can get the directory of the file and join (os.path.join()
) the image filename. e.g.:
import pygame
import os
# get the directory of this file
sourceFileDir = os.path.dirname(os.path.abspath(__file__))
iconPath = os.path.join(sourceFileDir, 'reindeer.png')
icon = pygame.image.load(iconPath)
pygame.display.set_icon(icon)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…