【发布时间】:2020-01-22 10:50:15
【问题描述】:
我对下面的代码有奇怪的行为。 当我从 PyCharm 级别运行此代码时,它可以正常工作并返回此窗口(包括带有 Python 徽标的 gif!): Window with Python logo
当我运行相同的 python 代码但使用 .bat 和 .vbs 文件时。它会给我这样的错误:
还有一件事... ".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