此代码有效:
import tkinter
root = tkinter.Tk()
canvas = tkinter.Canvas(root)
canvas.grid(row = 0, column = 0)
photo = tkinter.PhotoImage(file = './test.gif')
canvas.create_image(0, 0, image=photo)
root.mainloop()
它显示了我的图像。
现在,这段代码编译了,但它没有向我显示图像,我不知道为什么,因为它是相同的代码,在一个类中:
import tkinter
class Test:
def __init__(self, master):
canvas = tkinter.Canvas(master)
canvas.grid(row = 0, column = 0)
photo = tkinter.PhotoImage(file = './test.gif')
canvas.create_image(0, 0, image=photo)
root = tkinter.Tk()
test = Test(root)
root.mainloop()
答案 0 :(得分:40)
变量photo
是一个局部变量,在实例化类之后会收集垃圾。保存对照片的引用,例如:
self.photo = tkinter.PhotoImage(...)
如果您在“tkinter图片无法显示”上进行Google搜索,则第一个结果是:
http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm
答案 1 :(得分:0)
只需将global photo
添加为函数内的第一行。
答案 2 :(得分:0)
from tkinter import *
from PIL import ImageTk, Image
root = Tk()
def open_img():
global img
path = r"C:\.....\\"
img = ImageTk.PhotoImage(Image.open(path))
panel = Label(root, image=img)
panel.pack(side="bottom", fill="both")
but1 = Button(root, text="click to get the image", command=open_img)
but1.pack()
root.mainloop()
只需将global添加到img定义中,它将起作用