【问题标题】:Opening a file from other directory in Python [duplicate]在Python中从其他目录打开文件[重复]
【发布时间】:2020-04-28 16:39:20
【问题描述】:

我有一个 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 文件。

【问题讨论】:

  • 它指的是你的项目路径,而不是你运行代码时的文件路径。试试"resources/icon.png"
  • 没有任何区别。发生同样的错误。 @jizhihaoSAMA

标签: python python-3.x tkinter python-3.7


【解决方案1】:

你可以从__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))

【讨论】:

  • 谢谢!现在该错误已被删除。但是,现在出现了一个新的错误。它说:_tkinter.TclError: can't use "pyimage8" as iconphoto: not a photo image@AbbeGijly
【解决方案2】:

如果您使用相对路径,您将受制于当前工作目录,可能并不总是(...)/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')

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

【讨论】:

    猜你喜欢
    • 2016-05-10
    • 2016-08-17
    • 1970-01-01
    • 2017-07-31
    • 2015-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    相关资源
    最近更新 更多