【python】關於_tkinter.TclError: image "pyimage1" doesn't exist 問題的解決辦法
阿新 • • 發佈:2019-02-14
原始碼如下:
from tkinter import * from tkinter.filedialog import askopenfilename from PIL import Image,ImageTk class mainapp: def __init__(self): root=Tk() root.title("Several") root.geometry('200x300') Button(root,text='自動取點',command=self.another1).place(relx=0.3,rely=0.15,anchor=CENTER) Button(root,text='圖片翻轉').place(relx=0.7,rely=0.15,anchor=CENTER) root.mainloop() def another1(self): qudian() def another2(self): fanzhuan class qudian: def __init__(self): r1=Tk() r1.title('自動取點') r1.geometry('400x400') Label(r1,text='圖片路徑:').place(relx=0,rely=0.04) e1=Entry(r1) e1.place(relx=0.15,rely=0.04) Button(r1,text='選擇圖片').place(relx=0.52,rely=0.02) Label(r1,text="所選擇的圖片:").place(relx=0,rely=0.13) img_open=Image.open('desert.jpg') img_open.thumbnail((200,200)) img=ImageTk.PhotoImage(img_open) l1=Label(r1,image=img) l1.place(relx=0,rely=0.18) r1.mainloop() class fanzhuan: def __init__(self): r2=Tk() r2.mainloop() mainapp()
執行以後報錯:
之後去網上查瞭解決辦法,在 https://zhidao.baidu.com/question/1800925191188288187.html 這個網址下找到了正確答案。因為在一個程式中只能存在一個根視窗,也就是說只能存在一個Tk(),其他的視窗只能以頂層視窗(Toplevel())的形式存在。
於是將qudian類下的Tk()改成Toplevel()後,問題完全解決。
修改後的程式碼:
class qudian: def __init__(self): r1=Toplevel() r1.title('自動取點') r1.geometry('400x400') Label(r1,text='圖片路徑:').place(relx=0,rely=0.04) e1=Entry(r1) e1.place(relx=0.15,rely=0.04) Button(r1,text='選擇圖片').place(relx=0.52,rely=0.02) Label(r1,text="所選擇的圖片:").place(relx=0,rely=0.13) img_open=Image.open('desert.jpg') img_open.thumbnail((200,200)) img=ImageTk.PhotoImage(img_open) l1=Label(r1,image=img) l1.place(relx=0,rely=0.18) r1.mainloop()