在python脚本中嵌入图标

mau*_*ius 9 python icons exe tkinter pyinstaller

有没有人知道在Python脚本中嵌入图标的方法,这样当我创建独立的可执行文件(使用pyinstaller)时,我不需要包含.ico文件?我知道这可能与py2exe,但在我的情况下,我必须使用Pyinstaller,因为我没有成功使用前者.我正在使用Tkinter.

我知道iconbitmap(iconName.ico)但如果我想制作一个可执行的文件,那就行不通了.

Sau*_*ila 14

实际上,函数iconbitmap只能接收文件名作为参数,因此需要有一个文件.您可以在链接后面生成图标的Base64版本(字符串版本),上传文件并将结果作为变量字符串复制到源文件中.将其解压缩到临时文件,最后将该文件传递给iconbitmap并将其删除.这很简单:

import base64
import os
from Tkinter import *
##The Base64 icon version as a string
icon = \
""" REPLACE THIS WITH YOUR BASE64 VERSION OF THE ICON
"""
icondata= base64.b64decode(icon)
## The temp file is icon.ico
tempFile= "icon.ico"
iconfile= open(tempFile,"wb")
## Extract the icon
iconfile.write(icondata)
iconfile.close()
root = Tk()
root.wm_iconbitmap(tempFile)
## Delete the tempfile
os.remove(tempFile)
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!


fre*_*rho 8

你可能不需要这个,但是其他人可能会觉得这很有用,我发现你可以在不创建文件的情况下做到这一点:

import Tkinter as tk

icon = """
    REPLACE THIS WITH YOUR BASE64 VERSION OF THE ICON
    """

root = tk.Tk()
img = tk.PhotoImage(data=icon)
root.tk.call('wm', 'iconphoto', root._w, img)
Run Code Online (Sandbox Code Playgroud)


D4L*_*I3N 5

ALI3N 的解决方案

按着这些次序:

  1. 像这样编辑你的 .spec 文件:
a = Analysis(....)
pyz = PYZ(a.pure)
exe = EXE(pyz,
          a.scripts,
          a.binaries + [('your.ico', 'path_to_your.ico', 'DATA')], 
          a.zipfiles,
          a.datas, 
          name=....
       )
Run Code Online (Sandbox Code Playgroud)
  1. 将其添加到您的脚本中:
datafile = "your.ico" 
if not hasattr(sys, "frozen"):
    datafile = os.path.join(os.path.dirname(__file__), datafile) 
else:  
    datafile = os.path.join(sys.prefix, datafile)
Run Code Online (Sandbox Code Playgroud)
  1. 这样使用它:
root = tk.Tk()
root.iconbitmap(default=datafile)
Run Code Online (Sandbox Code Playgroud)

因为在使用 Pyinstaller 编译脚本后这将不起作用:

root = tk.Tk()
root.iconbitmap(default="path/to/your.ico")
Run Code Online (Sandbox Code Playgroud)

我的信息:python3.4,pyinstaller3.1.1