如何为与 PyInstaller 捆绑的 Windows、MacOS 和 Linux 应用程序创建快捷方式图标

How to create shortcut icons for Windows, MacOS and Linux applications bundled with PyInstaller

我正在构建一个与 PyInstaller 捆绑在一起的 Python 应用程序,它可用于 Windows、Linux(作为 AppImage)和 MacOS。

我需要这些的快捷方式图标。我有一个徽标,但我正在努力将其转换为正确的格式。在我看来,这三个平台都使用不同的图标大小和格式。

是否有任何 online/offline 生成器允许我从一个 jpg 文件为所有三个平台创建图标?

汤姆!我为您找到了解决方案!前往 here 站点并将您的图像转换为 icns 格式。然后在 pyinstaller 运行 命令中:-

pyinstaller pythonfile.py -F --i=icon_name.icns -noconsole

它工作正常。

如果您想将图标添加到 windows 文件中的 python.py,请尝试这些:-

如果您使用的是 pygame,请使用此代码:-

icon = pygame.image.load('icon.png')
pygame.display.set_icon(icon)

如果您使用的是 TKinter,请使用此代码:-

screen = Tk()

photo = PhotoImage(file = "Any image file")
screen.iconphoto(False, photo)

如果你想在文件完成后添加图标使用Pyinstaller:-

pip install pyinstaller

并且在 pyinstaller 中使用这个命令:-

pyinstaller pythonfile.py -F --i icon_name.ico -noconsole

关于它的一些信息:-

  • -F 表示 1 个文件,因此不会创建很多文件。只有 1 个将是 .exe 文件本身。
  • 访问此站点了解更多信息this site
  • 如果您不使用 GUI,请使用此命令:pyinstaller pythonfile.py -F --i icon_name.ico -nowindowed

希望对您有所帮助!

如果您想将 PNG 转换为 ICO 格式,可以使用 this 之类的 PNG 到 ICO 转换器(在线)。由于所有平台都支持 .ICO 格式文件,这将是您的一站式服务。

首选图标大小是 96px x 96px(高质量)或 48px x 48px(中等质量)的正方形。

此外,要使用 pyinstaller 为您的应用程序设置图标,您可以在使用命令行创建安装程序时指定图标的路径。

pyinstaller --onefile --windowed --icon=app.ico app.py

这将创建一个安装程序,其中包含一个带有指定图标的应用程序。

正如您提到的,您只需要将徽标从 jpg 转换为相应 OS 的图标文件,然后尝试 Pillow 的图像转换器。 此代码将为所有 (Mac, Win, Linux)

生成图标文件
from PIL import Image
filename = r'logo.jpg' # the directory of logo file
img = Image.open(filename) # reads the JPG file

# Generate and save the logo files
img.save('Win_logo.ico')   # On windows, icon file extension is .ico
img.save('Mac_logo.icns')  # On Mac OS, icon file extension is .icns
# Note: Creating icns requires Mac OS
img.save('Linux_logo.png') # in case if your AppImage requires any logo file

您可以选择指定所需的图标大小(Windows):

icon_sizes = [(16,16), (32, 32), (48, 48), (64,64)]
img.save('logo.ico', sizes=icon_sizes)

Pillow docs 说默认情况下它会生成尺寸 [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (255, 255)] 任何大于原始尺寸或 255 的尺寸都将被忽略。

查看 Pillow docs 了解更多信息。

因为 Pyinstaller 是基于 OS 并且 ICNS 也是基于 OS 生成的

更多 OS 指定

from platform import system as OS_Name
os_name = OS_Name()
filename = r'logo.jpg' # the directory of logo file
img = Image.open(filename) # reads the JPG file

# Generate and save the logo files
if os_name == 'Windows': img.save('Win_logo.ico')   # On windows, icon file extension is .ico
if os_name == 'Darwin' : img.save('Mac_logo.icns')  # On Mac OS, icon file extension is .icns
# on Linux the os_name is 'Linux'
img.save('Linux_logo.png') # in case if your AppImage requires any logo file

OS 独立于 ICNS

最好的os独立方式是在线方式。 Cloud Convert 是一个很好的工具。但是,您必须先将 jpg 转换为 png。 [注意:始终尝试对 logos 使用 png,因为它们具有透明度并且更方便] 您可以使用上述代码的 PNG 部分将您的 JPG 自动转换为 PNG,或使用 JPG to PNG 最后使用 PNG to ICNS.

转换您的 PNG 文件

直接使用auto-py-to-exe会更简单,它使用pyinstaller,但它会自动生成命令,因此您只需将图像上传到GUI