今天!,我正在嘗試使用 tkinter 創建一個影像查看器應用程式,我撰寫的代碼似乎得到了錯誤_tkinter.TclError: couldn't recognize data in image file "system_drive/boat.jpg"。但除此之外,據我所知,我收到此錯誤不應該是任何原因,該檔案boat.jpg存在于檔案夾中system_drive,而且我也沒有犯任何語法錯誤,感謝您的幫助!
代碼:
from tkinter import *
import os
tk = Tk()
image_list = []
for file in os.listdir(os.getcwd()):
if file.endswith(".png") or file.endswith(".jpg"):
image_list.append(PhotoImage(file))
file_name = Entry(tk, width=20,font=("Helvetica", 20))
canvas = Canvas(tk, width=500, height=500)
canvas.pack()
def click_show_img(x):
global file_name
global image_list
print("opening system_drive/{0}".format(file_name.get()))
img = PhotoImage(file="system_drive/{0}".format(file_name.get()))
canvas.create_image(60,60, anchor=NW, image=img)
tk.bind("<Return>", click_show_img)
file_name.pack()
tk.mainloop()
截圖:
視窗的樣子:

它應該是什么樣子:

uj5u.com熱心網友回復:
Tkinter 不支持 jpeg 作為影像格式。如果要顯示 .jpg 檔案,則需要使用Pillow或其他庫來打開它。
來自 tk 的官方檔案:
目前僅支持 PNG、GIF 和 PPM/PGM 格式
這就是 tkinter 說它無法識別資料的原因。它與路徑無關,與檔案中資料的格式有關。) 或其他一些庫來打開它。
來自 tk 的官方檔案:
目前僅支持 PNG、GIF 和 PPM/PGM 格式
這就是 tkinter 說它無法識別資料的原因。它與路徑無關,與檔案中資料的格式有關。
你還有另一個問題。如果不保存對影像的參考,python 的垃圾收集器將在函式回傳時洗掉影像資料。看來您已經有一個包含影像的全域陣列,所以我不明白您為什么要創建新影像。
img = PhotoImage(file="system_drive/{0}".format(file_name.get()))
image_list.append(img)
請參閱為什么在函式中創建 Tkinter 影像不顯示? 了解更多資訊。
代碼開頭的第三個問題是您必須將檔案名PhotoImage作為file屬性值而不是位置引數傳遞給。第一個位置引數被視為名稱,而不是路徑。
image_list.append(PhotoImage(file=file))
uj5u.com熱心網友回復:
您需要 Pillow 庫來打開影像并將其顯示在 tkinter 視窗上。
from PIL import Image, ImageTk
將您的 click_show_img 函式更改為:
def click_show_img(x):
global file_name
global image_list
print("opening system_drive/{0}".format(file_name.get()))
img = Image.open("opening system_drive/{0}".format(file_name.get()))
img = ImageTk.PhotoImage(img)
canvas.create_image(60, 60, anchor=NW, image=img)
uj5u.com熱心網友回復:
我已經設法解決了我的代碼的問題;我創建了一個新的標簽實體,然后像這樣更新該標簽實體的影像:
from tkinter import *
import os
from PIL import Image, ImageTk
tk = Tk()
image_list = []
image_holder = Label()
for file in os.listdir(os.getcwd()):
if file.endswith(".png"):
image_holder.image = PhotoImage(name)
img = PhotoImage(file="system_drive/{0}".format(file_name.get()))
image_list.append(img)
image_holder.place(x=-10,y=-10)
file_name = Entry(tk, width=20,font=("Helvetica", 20))
canvas = Canvas(tk, width=500, height=500)
canvas.pack()
my_label = Label(tk,bg="white")
my_label.place(x=-10,y=-20)
def click_show_img(x):
global file_name
global image_list
print("opening system_drive/{0}".format(file_name.get()))
link = "system_drive/{0}".format(file_name.get())
my_img = ImageTk.PhotoImage(Image.open(link).resize((250,250)))
my_label.configure(image=my_img)
my_label.image = my_img
my_label.place(relx=0.5,rely=0.3,anchor=CENTER)
tk.bind("<Return>", click_show_img)
file_name.pack()
tk.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/465744.html
上一篇:如何在帶有GUI的python游戲中設定回答時間限制?
下一篇:截圖工具無法截取左側截圖
