【发布时间】:2020-05-12 19:38:03
【问题描述】:
我正在创建一个 tkinter 应用程序,在该应用程序中我使用自定义按钮图像以及自定义按钮类,以使按钮具有悬停效果。当图像和脚本位于同一文件夹中时,脚本运行良好,但是,一旦我尝试使用“os”或“path”模块,python 就会给我这个错误。
“_tkinter.TclError:图像“N:\Year 13\Computer Science\Project\AMFC\Project files/Buttons/App button.gif”不存在”
我确保图像确实存在于路径中,并尝试基于“os.getcwd()”和“os.path.join”以及等效的“路径”模块构建路径。我也试过建立图片的绝对路径,但是还是不行。
work_folder = os.path.dirname(os.path.abspath(__file__))
button_path = os.path.join(work_folder, "Project files/Buttons")
这是我的自定义按钮类:
class Button(tk.Button):
def __init__(self, parent, default_background="", hover_background="", **kwargs):
tk.Button.__init__(self, master=parent, **kwargs)
self.default_background = tk.PhotoImage(file=default_background)
self.hover_background = tk.PhotoImage(file=hover_background)
self.configure(image=self.default_background)
self.bind("<Enter>", self.on_enter)
self.bind("<Leave>", self.on_leave)
def on_enter(self, event):
self.configure(image=self.hover_background)
def on_leave(self, event):
self.configure(image=self.default_background)
这是我的应用方式:
import Customised_Widgets as cw
cw.Button(self, text="Pure Core", default_background=os.path.join(button_path, "App button.gif"),
hover_background=os.path.join(button_path, "Project files/Buttons/App button(hover).gif"),
relief=tk.FLAT,highlightcolor="#E7E6E6",highlightbackground="#E7E6E6",
bg="#E7E6E6", bd=0, padx=0, pady=0, borderwidth=0,
highlightthickness=0, compound="center").place(x=434, y=270)
我在一个单独的模块中创建了该按钮,以使我的工作更有条理。这个单独的模块与主脚本位于同一文件夹中。
我不知道该怎么办,我尝试为图像提供完整的路径名,但仍然没有用。它拒绝检测我指向 tkinter 的文件夹中的图像,即使它确实存在......
任何帮助将不胜感激。
【问题讨论】:
-
为了便于阅读,我会在按钮之外定义您的路径。
-
您似乎在路径中同时使用了
/和``。这可能是问题的一部分。一个简单的事实是,如果你给 python 一个有效的路径,它会找到该文件。如果它说找不到文件,则说明您提供的路径无效。 -
感谢两位的回复。为了更好的可读性,我在按钮外部的变量中定义了路径,并且所有斜线在整个路径中都是相同的。我用 os.path.exists() 检查了路径是否存在,它返回 true。我不知道还能做什么......
-
button_path已经包含Project files/buttons,所以hover_background=os.path.join(button_path, "Project files/Buttons/App button(hover).gif")应该是hover_background=os.path.join(button_path, "App button(hover).gif")?
标签: python tkinter operating-system