【问题标题】:How do I bundle my tkinter based application with my custom icon?如何将基于 tkinter 的应用程序与自定义图标捆绑在一起?
【发布时间】:2020-03-16 07:50:57
【问题描述】:

我有一个基于 tkinter 的应用程序,其结构如下:

import tkinter as tk

class App(tk.Frame):
    def __init__(self, master):
        self.master = master
        tk.Frame.__init__(self, self.master)
        self.configure_gui()
        self.create_widgets()

    def configure_gui(self):
        self.master.iconbitmap("my_logo.ico")
        self.master.title("Example")
        self.master.minsize(250, 50)

    def create_widgets(self):
        self.label = tk.Label(self.master, text="hello world")
        self.label.pack()


if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()

当我从命令行运行 .py 文件时,我的徽标会按预期替换应用程序主窗口中的默认 tkinter 羽毛徽标。我什至可以使用以下命令冻结我的应用程序并将其与 pyinstaller 捆绑在一起:

pyinstaller -i my_logo.ico my_application.py

不幸的是,当我尝试运行此进程生成的 .exe 文件时,遇到以下错误:

Traceback (most recent call last):
  File "my_application.py", line 22, in <module>
  File "my_application.py", line 7, in __init__
  File "my_application.py", line 11, in configure_gui
  File "tkinter\__init__.py", line 1865, in wm_iconbitmap
_tkinter.TclError: bitmap "my_logo.ico" not defined
[5200] Failed to execute script my_application

我已经搜索了这个网站和其他网站,以寻找适合我的解决方案,但没有找到。任何方向将不胜感激!

【问题讨论】:

  • 可执行文件本身带有正确的标识。所以不幸的是,我不认为这是问题所在。
  • 你是对的,我误解了这个问题,tkinter 找不到图标,因为它不包括在内。我最近在这里发布了我的解决方法:stackoverflow.com/a/58630674/4777984

标签: python image user-interface tkinter pyinstaller


【解决方案1】:

我发现将图像存储为.py 模块对我来说更容易,然后 PyInstaller 会像处理任何其他模块一样处理它,并使用基本命令行命令使 exe 工作而无需任何特殊:

制作image.py文件的脚本:

import base64
with open("my_logo.ico", "rb") as image:
    b = base64.b64encode(image.read())
with open("image.py", "w") as write_file:
    write_file.write("def icon(): return (" + str(b) + ")"

然后将模块导入为镜像:

import tkinter as tk
import image

class App(tk.Frame):
    def __init__(self, master):
        self.master = master
        tk.Frame.__init__(self, self.master)
        self.configure_gui()
        self.create_widgets()

    def configure_gui(self):
        self.master.tk.call('wm', 'iconphoto', self.master._w, tk.PhotoImage(data=image.icon()))
        self.master.title("Example")
        self.master.minsize(250, 50)

    def create_widgets(self):
        self.label = tk.Label(self.master, text="hello world")
        self.label.pack()


if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()

否则你基本上必须在构建命令中调用添加.ico文件,然后在你的脚本中需要添加行以确定解压的pyinstaller-packed脚本的目录在哪里,然后调整你的路径到打包的@987654327 @ 文件。

在此讨论:Bundling data files with PyInstaller (--onefile)

但我发现自己的方式更容易。

【讨论】:

    猜你喜欢
    • 2013-03-16
    • 2018-09-13
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-19
    • 2017-02-27
    • 2015-07-09
    相关资源
    最近更新 更多