出现的问题
from tkinter import * from PIL import Image, ImageTk root = Tk() root.title('按钮点击加载图片') def show(): img = Image.open('1.png') # 打开图片 photo = ImageTk.PhotoImage(img) # 用PIL模块的PhotoImage打开 imglabel = Label(root, image=photo) imglabel.grid(row=0, column=0, columnspan=3) btn = Button(root, text="show", command=show) btn.grid(row=1, column=1) mainloop()运行结果
图片无法正常显示
重点:将参数设置成全局变量
photo=None img=None上代码
from tkinter import * from PIL import Image, ImageTk root = Tk() root.title('按钮点击加载图片') photo=None img=None def show(): global photo global img img = Image.open('1.png') # 打开图片 photo = ImageTk.PhotoImage(img) # 用PIL模块的PhotoImage打开 imglabel = Label(root, image=photo) imglabel.grid(row=0, column=0, columnspan=3) btn = Button(root, text="show", command=show) btn.grid(row=1, column=1) mainloop()运行结果