从 Python 中的其他目录打开文件

Opening a file from other directory in Python

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

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

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

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

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

您可以从__file__获取到icon.png的相对路径,也就是您当前源文件的路径:

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

然后

...  root.iconphoto(False, tk.PhotoImage(file=rcfile))

如果您使用相对路径,您将受制于您当前的工作目录,该目录可能并不总是 (...)/root/windows。您当前的目录很可能是您执行 Python executable/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')

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