-3

我有一个 tkinter python 文件保存在目录的文件夹中。该文件的图标和其他资源保存在另一个文件夹中。

root_directory
|
|---resources
|   |
|   |---icon.png
|
|---windows
|   |
|   |---tkinter_file.py

tkinter_file.py中,我想为 tkinter 窗口设置一个图标。所以,我做了类似的事情: root.iconphoto(False, tk.PhotoImage(file='../resources/icon.png'))

但是,这显示了一个错误: _tkinter.TclError: couldn't open "../resources/icon-appointment.png": no such file or directory

请帮助我成功找到位于不同文件夹中的 PNG 文件。

4

2 回答 2

2

您可以获取icon.pngfrom的相对路径__file__,即当前源文件的路径:

import os
thisdir = os.path.dirname(__file__)
rcfile = os.path.join(thisdir, '..', 'resources', 'icon.png')

然后

...  root.iconphoto(False, tk.PhotoImage(file=rcfile))
于 2020-04-28T17:06:15.063 回答
1

如果您使用相对路径,您将受到当前工作目录的支配,这可能并不总是(...)/root/windows. 您的当前目录很可能是您执行 Python 可执行文件/shell 的任何位置。您需要使用绝对路径或更新当前目录:

import os
os.chdir('(...)/root_directory') # fill in your absolute path to root_directory

一种不优雅的方法是将目录更改为当前.py文件所在的位置,然后返回:

cur_dir = os.path.dirname(__file__)
os.chdir(os.path.join(cur_dir, '../resources/icon-appointment.png')

更合适的方法是将脚本作为模块运行,以便保留项目结构。

于 2020-04-28T17:06:43.723 回答