How should I solve the error _tkinter.TclError: couldn't open "sample.png": no such file or directory
How should I solve the error _tkinter.TclError: couldn't open "sample.png": no such file or directory
我的代码与我的图像位于同一个文件夹中。
我是新手,所以我不确定,但这可能是我的 IDE(visual studio 代码)
我试过使用 PLE??但这没有用
import tkinter as tk
HEIGHT = 700
Width = 800
root = tk.Tk()
canvas = tk.Canvas(root, height = HEIGHT , width = Width)
canvas.pack()
background_image = tk.PhotoImage(file = "sample.png")
back_label = tk.Label(root,Image = background_image)
back_label.place(relwidth = 1 ,relheight = 1)
root.mainloop()
首先,我认为您应该使用整个图像路径(我不确定,但我正在使用 ubuntu,我应该使用完整路径)。然后我稍微更改一下代码,这对我有用
import tkinter as tk
HEIGHT = 700
Width = 800
root = tk.Tk()
canvas = tk.Canvas(root, height = HEIGHT , width = Width)
canvas.pack()
background_image=tk.PhotoImage(file = "sample.png")
background_label = tk.Label(root, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
root.mainloop()
无法打开“sample.png”:没有这样的文件或目录意味着您的文件不在正确的位置您有 2 个选择,要么将其移动到启动它的位置,要么使用绝对路径
如果您通过终端执行 python 脚本,那么执行脚本的位置也可能会有所不同。例如,如果您 运行 从 /home/usrname 执行脚本并执行类似 >> ./downloads/src/run.py 的操作,您的相对路径将是 /home/usrname/,而不是 /home/usrname/下载/src/。如果您导航到该文件夹并尝试 运行 python 脚本,它可能会突然找到该图像。
所以解决方案是为图像使用完全限定的路径,或者可能有更好的方法来设置相对路径。 idk
我的代码与我的图像位于同一个文件夹中。 我是新手,所以我不确定,但这可能是我的 IDE(visual studio 代码)
我试过使用 PLE??但这没有用
import tkinter as tk
HEIGHT = 700
Width = 800
root = tk.Tk()
canvas = tk.Canvas(root, height = HEIGHT , width = Width)
canvas.pack()
background_image = tk.PhotoImage(file = "sample.png")
back_label = tk.Label(root,Image = background_image)
back_label.place(relwidth = 1 ,relheight = 1)
root.mainloop()
首先,我认为您应该使用整个图像路径(我不确定,但我正在使用 ubuntu,我应该使用完整路径)。然后我稍微更改一下代码,这对我有用
import tkinter as tk
HEIGHT = 700
Width = 800
root = tk.Tk()
canvas = tk.Canvas(root, height = HEIGHT , width = Width)
canvas.pack()
background_image=tk.PhotoImage(file = "sample.png")
background_label = tk.Label(root, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
root.mainloop()
无法打开“sample.png”:没有这样的文件或目录意味着您的文件不在正确的位置您有 2 个选择,要么将其移动到启动它的位置,要么使用绝对路径
如果您通过终端执行 python 脚本,那么执行脚本的位置也可能会有所不同。例如,如果您 运行 从 /home/usrname 执行脚本并执行类似 >> ./downloads/src/run.py 的操作,您的相对路径将是 /home/usrname/,而不是 /home/usrname/下载/src/。如果您导航到该文件夹并尝试 运行 python 脚本,它可能会突然找到该图像。
所以解决方案是为图像使用完全限定的路径,或者可能有更好的方法来设置相对路径。 idk