pygame 无法正确显示图标 [英] Icons are not displayed properly with pygame

查看:106
本文介绍了pygame 无法正确显示图标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

图标不显示,关闭半秒才显示:

The icon is not displayed, it's only displayed after closing for half a second:

screen = pygame.display.set_mode((1600, 900)) 
pygame.display.set_caption(‘Elizabeth2’) 
icon = pygame.image.load('reindeer.png') 
pygame.display.set_icon(icon) 

推荐答案

参见 pygame.display.set_icon():

[...] 某些系统不允许窗口图标在显示后更改.可以在pygame.display.set_mode()之前调用这个函数来在设置显示模式之前创建图标.

[...] 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.

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:

[...] 您可以通过任何表面,但大多数系统都需要 32x32 左右的较小图像.

[...] 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.

图像文件路径必须相对于当前工作目录.工作目录可能与python文件的目录不同.

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.

文件名和路径可以通过__file__.当前工作目录可以通过 os.getcwd() 获取 并且可以通过 os.chdir(path).

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)

另一种解决方案是找到绝对路径.如果图片是相对于python文件所在的文件夹(甚至在同一个文件夹中),那么就可以获取文件所在的目录并加入(os.path.join()) 图像文件名.例如:

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)

这篇关于pygame 无法正确显示图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆