存在問題:
代碼寫在主函數中,圖可以正常顯示,如下:
import tkinter as tk
root = tk.Tk() #定義一個tkinter類root; Tkinter為圖形界面庫
root.title("随機點名") #标題
root.geometry('550x450') #窗體尺寸
img = r'F:\PythonFiles\PycharmFile\ex11CharacterGraph2_GraphIn.png'
photo = tk.PhotoImage(file=img)
labelImg = tk.Label(root, image=photo)
label.image = photo
labelImg.pack(side=tk.TOP)
root.mainloop()
但是寫在類中,被引用時就無法顯示,如下:
def pic_label(self):
img = r'F:\PythonFiles\PycharmFile\ex11CharacterGraph2_GraphIn.png'
photo = tk.PhotoImage(file=img)
labelImg = tk.Label(self, image=photo)
label.image = photo
labelImg.pack(side=tk.TOP)
import tkinter as tk
root = tk.Tk() #定義一個tkinter類root; Tkinter為圖形界面庫
root.title("随機點名") #标題
root.geometry('550x450') #窗體尺寸
pic_label(root) #調用函數
root.mainloop()
解決方案:
在圖形顯示代碼後加入必要的兩句代碼
labelImg.config(image=photo)
labelImg.image = photo
修正後完整代碼如下:
def pic_label(self):
img = r'F:\PythonFiles\PycharmFile\ex11CharacterGraph2_GraphIn.png'
photo = tk.PhotoImage(file=img)
labelImg = tk.Label(self, image=photo)
labelImg.pack(side=tk.TOP)
# 以下補充的兩句代碼非常重要,是保證圖在函數中可以被加載的途徑
labelImg.config(image=photo)
labelImg.image = photo
import tkinter as tk
root = tk.Tk()
root.title("随機點名") #标題
root.geometry('550x450') #窗體尺寸
pic_label(root) #調用函數
root.mainloop()