简体   繁体   English

Tkinter没有按预期将图像放在按钮上

[英]Tkinter doesn't put images on buttons as expected

I'm creating images using PIL, not saving them anywhere because they will be different every time and trying to put those images on buttons. 我正在使用PIL创建图像,而不是将它们保存在任何地方,因为它们每次都不同,因此尝试将这些图像放在按钮上。 The problem is, for some reason that only the last image gets put on the button. 问题是,由于某种原因,只有最后一张图像被放置在按钮上。 This is my code: 这是我的代码:

from PIL import ImageDraw
from PIL import ImageFont
from Tkinter import *

master = Tk()
W, H = (70,70)

from PIL import Image
from PIL import ImageTk

def fun(meth):
    print meth
    return
for i in range(0,5):
    img = Image.new("RGB", (W, H), (255,0,0))
    draw = ImageDraw.Draw(img)
    text_string = str(i)+','+str(i+1)
    font = ImageFont.truetype("arial.ttf", 25)
    w, h = draw.textsize(text_string, font=font)
    draw.text(((W-w)/2,(H-h)/2), str(i)+','+str(i+1),(0,0,0), font=font )


    imagetk = ImageTk.PhotoImage(img)
    b = Button(master, image=imagetk, command=lambda method=text_string: fun(method))
    b.grid(row=0, column=i, padx=20)

    #img.save(path+'.png', "PNG")

master.mainloop()



For me, output for this program looks like this 对我来说,该程序的输出如下所示 在此处输入图片说明


I'm saving images to disk in the end of the loop and I'm seeing other images created just as expected, but for some reason they don't get put on the other buttons. 我在循环结束时将图像保存到磁盘,并且看到按预期方式创建了其他图像,但是由于某些原因,它们没有放在其他按钮上。 Also I just now noticed that other buttons don't even respond to click, only the last one behaves as expected. 我刚才也注意到其他按钮甚至不响应单击,只有最后一个按钮的行为符合预期。

You didn't create an external reference. 您没有创建外部参考。 I simply added a refs list and now it works fine: 我只是添加了一个refs列表,现在工作正常:

refs = [] # new
for i in range(0,5):
    img = Image.new("RGB", (W, H), (255,0,0))
    draw = ImageDraw.Draw(img)
    text_string = str(i)+','+str(i+1)
    font = ImageFont.truetype("arial.ttf", 25)
    w, h = draw.textsize(text_string, font=font)
    draw.text(((W-w)/2,(H-h)/2), str(i)+','+str(i+1),(0,0,0), font=font )


    imagetk = ImageTk.PhotoImage(img)
    b = Button(master, image=imagetk, command=lambda method=text_string: fun(method))
    b.grid(row=0, column=i, padx=20)
    refs.append(imagetk) # new

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM