【问题标题】:How do I locally reference files in my python project?如何在我的 python 项目中本地引用文件?
【发布时间】:2021-10-04 19:26:03
【问题描述】:

我正在尝试创建一个 exe“游戏”(更多的是概念验证),但是当我这样做时,图像文件不显示。 :

parentDirectory = os.path.abspath(os.path.join(os.getcwd(), os.pardir))
photo = tk.PhotoImage(file = os.path.join(parentDirectory, 'okokokokok1.1','imgs', 'spooky.PNG'),width=320,height=240)

老实说,我不明白有什么问题,请帮助 thx ;3

【问题讨论】:

  • os.getcwd() 不一定是当前正在执行的 python 模块所在的目录。试试打印吧。
  • 你应该使用os.path.dirname(os.path.abspath(__file__)) 而不是os.getcwd(),因为getcwd 提供Current Working Directory,它不一定是Directory with Script
  • 您可能在PhotoImage 中遇到BUG 的常见问题,当您将PhotoImage 分配给局部变量时,它会从内存中删除图像。它可能需要分配给全局变量或其他类 - 即。标记将显示图像label.photo = tk.PhotoImage(...)。请参阅页面末尾的Note web.archive.org/web/20201112023229/http://effbot.org/… 这个问题在 Stackoverflow 上出现过很多次,如果您尝试搜索至少 PhotoImage problem,那么您应该在 SO 上找到解决方案

标签: python github


【解决方案1】:

@furas 解决了我的问题,谢谢。 他们的评论:

您应该使用os.path.dirname(os.path.abspath(__file__)) 而不是os.getcwd(),因为getcwd 提供Current Working Directory,而不必是Directory with Script

【讨论】:

    猜你喜欢
    • 2021-01-06
    • 1970-01-01
    • 2019-05-26
    • 2018-07-24
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    相关资源
    最近更新 更多