詳解python tkinter 圖片插入問題
通過tkinter.PhotoImage插入GIF, PGM/PPM格式的圖片。
import tkinterclass Gui: def __init__(self): self.gui=tkinter.Tk()# create gui window self.gui.title('Image Display') # set the title of gui self.gui.geometry('800x600') # set the window size of gui img = tkinter.PhotoImage(file='C:/Users/15025/Desktop/bear.gif') # read image from path label1=tkinter.Label(self.gui,image=img) # create a label to insert this image label1.grid() # set the label in the main window self.gui.mainloop() # start mainloopmain = Gui()
注意: img = tkinter.PhotoImage(file='C:/Users/15025/Desktop/bear.gif') 中的關鍵字file不能夠省略,否則程序無法正常顯示圖片。
對于常用的PNG,與JPG格式的圖片,我們需要從python image library(pillow)(PIL)導入Image與ImageTk模塊來實現,代碼如下:
import tkinterfrom PIL import Imagefrom PIL import ImageTkclass Gui: def __init__(self): self.gui=tkinter.Tk()# create gui window self.gui.title('Image Display') # set the title of gui self.gui.geometry('800x600') # set the window size of gui load = Image.open('C:/Users/15025/Desktop/1.png') # open image from path img = ImageTk.PhotoImage(load) # read opened image label1=tkinter.Label(self.gui,image=img) # create a label to insert this image label1.grid() # set the label in the main window self.gui.mainloop() # start mainloopmain = Gui()
然而在實際操作中,本人使用的是Anaconda spyder編譯器,當我們在讀入圖像時程序出錯后,再次運行程序就會導致image 'pyimage1' doesn’t exist錯誤,每次運行一次,數字就會增加1,如:image 'pyimage2' doesn’t exist。遇到此錯誤,可以直接在IPython控制臺界面重啟IPython內核即可,或者關閉編譯器并重新打開。
看似我們已經完全實現了圖片的插入,但是這種插入方法是存在隱患的,具體代碼如下:
import tkinter as tkfrom PIL import Imagefrom PIL import ImageTkclass Gui(tk.Tk): def __init__(self): super().__init__() self.title('Figure dynamic show v1.01') # self.geometry('1000x800+400+100') self.mainGui() # self.mainloop() def mainGui(self): image = Image.open('C:/Users/15025/Desktop/1.png') photo = ImageTk.PhotoImage(image) label = tk.Label(self, image=photo) label.image = photo # in case the image is recycled label.grid() main = Gui()main.mainloop()
這里我們可以看到相比較上面的程序,我們將Gui界面的圖像插入部分分離到另一個函數中,并且直接定義一個tkinter的類,這樣做的好處是我們可以直接用self替代創建的主窗口界面,并且我們可以在不同的地方啟動主循環,self.mainloop()和main.mainloop()任選一個即可。并且因為我們想要插入圖片,所以我們可以省略指定Gui界面的尺寸,這樣做的好處是會創建一個自適應圖片大小的Gui界面。最重要的是我們可以看到多了一行代碼label.image = photo,我們將選取的圖片photo賦值給了label的屬性對象image,如果沒有這一行代碼,圖片便無法正常顯示,這是因為python會自動回收不使用的對象,所以我們需要使用屬性對象進行聲明。 上述的程序隱患便是因為缺少了這一行代碼。
至此,tkinter的圖片插入可暫時告一段落。
到此這篇關于詳解python tkinter 圖片插入問題的文章就介紹到這了,更多相關python tkinter 圖片插入內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
