Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python tk.PhotoImage无法打开“gif”_Python_File_Tkinter_Directory_Photoimage - Fatal编程技术网

Python tk.PhotoImage无法打开“gif”

Python tk.PhotoImage无法打开“gif”,python,file,tkinter,directory,photoimage,Python,File,Tkinter,Directory,Photoimage,我有下面代码的奇怪行为。 当我从PyCharm级别运行此代码时,它工作正常,并返回此窗口,包括带有Python徽标的gif!: 当我运行相同的python代码但使用.bat和.vbs文件时。它会给我这样的错误: 还有一件事。打开windows操作系统时,会自动启动vbs文件。vbs文件打开.bat文件和.bat文件打开.py文件 您知道为什么python代码在windows操作系统上启动时无法找到.gif吗 以下是代码: import tkinter as tk class KeypadTes

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

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

还有一件事。打开windows操作系统时,会自动启动vbs文件。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()

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

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

您可以通过在程序中包含一行来进行实验,该行在启动时打印出工作目录

import os
print(os.getcwd()) 

从.bat文件运行脚本时,当前目录为C:\WINDOWS\system32\python,因此.gif文件不在当前目录中。当您从PyCharm运行代码时,当前目录可能被设置为其他目录。您可以通过使用os.path.dirname从预定义的_文件__变量提取脚本文件的目录,然后使用os.path.join将其附加到映像的文件名以获得文件的有效绝对路径来解决此问题。您是对的,此问题与文件本地化有关。当我从“.vbs”运行程序时,我需要显示文件“隐式”的路径,例如E:\images\my.gif或使用os.getcwd从所需目录运行python代码。谢谢您的帮助。