【问题标题】:tk.PhotoImage couldn`t open "gif"tk.PhotoImage 无法打开“gif”
【发布时间】:2020-01-22 10:50:15
【问题描述】:

我对下面的代码有奇怪的行为。 当我从 PyCharm 级别运行此代码时,它可以正常工作并返回此窗口(包括带有 Python 徽标的 gif!): Window with Python logo

当我运行相同的 python 代码但使用 .bat 和 .vbs 文件时。它会给我这样的错误:

Error

还有一件事... ".vbs" 文件会在 Windows(操作系统)打开时自动启动。 “.vbs”文件打开“.bat”文件,“.bat”文件打开“.py”文件。

你知道为什么python代码在windows操作系统下启动时找不到“.gif”吗?

代码如下:

import tkinter as tk
class KeypadTest():
    def __init__(self, master):
        self.master = master
        self.time_display = tk.IntVar()
        global logo
        logo = tk.PhotoImage(file="indeks_gif.gif")
        tk.Label(self.master, height=10, width=10 , textvariable=self.time_display,bg="red").pack(side="right")
        Info = """INFO"""
        tk.Label(self.master,compound = tk.CENTER,image=logo,text=Info).pack()
master = tk.Tk()
KT = KeypadTest(master)
master.mainloop()

【问题讨论】:

  • 当您从.bat 文件运行脚本时,当前目录为C:\WINDOWS\system32\python,因此.gif 文件将不在当前目录中。当您从 PyCharm 运行代码时,当前目录可能设置为其他目录。您可以通过使用os.path.dirname() 从预定义的__file__ 变量中提取脚本文件的目录,然后使用os.path.join() 将其附加到图像的文件名以获取文件的有效绝对路径来解决此问题。跨度>

标签: python file tkinter directory photoimage


【解决方案1】:

程序找不到文件。我怀疑这是因为您没有从 gif 文件所在的目录运行 Python 程序。

这可以通过提供图像的完整路径或从该目录运行 bat 文件来解决,无论 bat 文件位于何处。我没有尝试过使用 vbs 文件,但我认为问题是一样的。

你可以在你的程序中加入一行,当它启动时打印出工作目录。

import os
print(os.getcwd()) 

【讨论】:

  • 你是对的问题是连接文件本地化。当我从“.vbs”运行程序时,我需要显示文件“隐式”的路径,例如E:\images\my.gif ,或者使用os.getcwd()从所需目录运行python代码。谢谢你的帮助。
猜你喜欢
  • 2014-07-26
  • 2014-05-12
  • 2019-01-06
  • 2021-12-01
  • 2020-08-29
  • 2014-03-26
  • 1970-01-01
  • 2017-12-14
  • 2020-04-22
相关资源
最近更新 更多