首页 > 解决方案 > Python tkinter iconbitmap,onefile和exe的add-data

问题描述

我正在尝试将 tkinter 中的默认羽毛图标更改为个性化图标。我在同一个文件夹中有图标文件和 python 文件。在使用 pyinstaller 构建 exe 时,我也使用了 add-data。我在命令提示符中使用以下命令:

pyinstaller --add-data "full_path_and filename_of_icon_file;," -i "full_path_and filename_of_icon_file" scriptname.py

这似乎有效,因为“dist”文件夹包含 .ico 文件。

如果我使用 OneFile 参数: pyinstaller --onefile --add-data "full_path_and filename_of_icon_file;," -i "full_path_and filename_of_icon_file" scriptname.py

... dist 文件夹仅包含 exe,似乎找不到 .ico 文件,我得到一个 tkinter.TclError: bitmap "full_path_and filename_of_icon_file" not defined。

在我的脚本中,在定义图标文件路径时,我使用 os.getcwd + os.path.join 来获取 exe 文件的当前目录和 ico 文件的文件名(假设 add-data 会添加我的 ico 文件到exe)。但显然这不起作用。

有人可以指导我吗?最终,我无法在脚本中硬编码 .ico 文件路径,因为我不希望将 exe 文件和 .ico 文件分发给其他人;但我只想分发 .exe 文件。

以下是我的示例代码:

import tkinter as tk

OptionList = [
"Aries",
"Cancer"
] 

import sys, os

exe_path = os.getcwd()
ico_file = 'PSI_logo.ico'    # or use any .ico file here

ico_path = os.path.join(exe_path, ico_file)  # dynamically generating ico path

app = tk.Tk()

app.iconbitmap(ico_path)   # dynamically generated path
app.resizable(0,0)
app.geometry('100x200')

variable = tk.StringVar(app)
variable.set("")

opt = tk.OptionMenu(app, variable, *OptionList)
opt.config(width=90, font=('Helvetica', 12))
opt.pack()

def printselection():
    print(variable.get())
    variable.set("")

mybutton = tk.Button(app, text = 'Click', command = printselection)
mybutton.pack()

app.mainloop()

标签: tkinterexepyinstaller

解决方案


推荐阅读