Pycharm中tkinter图不被加载的处理方法

存在问题:
代码写在主函数中,图可以正常显示,如下:

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()

猜你喜欢

转载自blog.csdn.net/coberup/article/details/82979135
今日推荐