Python 3.x Tkinter从具有不同图像的列表创建按钮

Python 3.x Tkinter从具有不同图像的列表创建按钮,python-3.x,tkinter,Python 3.x,Tkinter,我想从一个列表中创建一个按钮,我希望它们有自己的图像。 我已经试过了,但只有最后创建的按钮起作用 liste_boutton = ['3DS','DS','GB'] for num,button_name in enumerate(liste_boutton): button = Button(type_frame) button['bg'] = "grey72" photo = PhotoImage(file=".\dbinb\img\\{}.png".format(

我想从一个列表中创建一个按钮,我希望它们有自己的图像。 我已经试过了,但只有最后创建的按钮起作用

liste_boutton = ['3DS','DS','GB']

for num,button_name in enumerate(liste_boutton):
    button = Button(type_frame)
    button['bg'] = "grey72"
    photo = PhotoImage(file=".\dbinb\img\\{}.png".format(button_name))
    button.config(image=photo, width="180", height="50")
    button.grid(row=num, column=0, pady=5, padx=8)

你的代码看起来不错,但你需要保留一个图像的参考,而且我相信PhotoImage只能读取,所以你需要另一个库PIL似乎是一个不错的选择。我使用了谷歌搜索中的一些图片,它们和我的.py文件放在同一个目录中,所以我稍微修改了代码。此外,如果不小心,按钮的宽度和高度可能会切断部分图像

from Tkinter import *
from PIL import Image, ImageTk
type_frame = Tk()

liste_boutton = ['3DS','DS','GB']

for num,button_name in enumerate(liste_boutton):
    button = Button(type_frame)
    button['bg'] = "grey72" 
    # this example works, if .py and images in same directory
    image = Image.open("{}.png".format(button_name))
    image = image.resize((180, 100), Image.ANTIALIAS) # resize the image to ratio needed, but there are better ways
    photo = ImageTk.PhotoImage(image) # to support png, etc image files
    button.image = photo # save reference
    button.config(image=photo, width="180", height="100")
    # be sure to check the width and height of the images, so there is no cut off
    button.grid(row=num, column=0, pady=5, padx=8)

mainloop()
输出:
[

只有您的最后一个按钮具有图像,因为它是全局范围内唯一具有引用的按钮,或者在您的特定情况下,在任何范围内都具有引用。因此,您只有一个可引用的按钮和图像对象,即
按钮
照片

简单的回答是:

photo = list()
for...
    photo.append(PhotoImage(file=".\dbinb\img\\{}.png".format(button_name)))

但这仍然会有很多不好的做法。

有了你的评论,我能够实现我的期望! 谢谢!我是编程新手,所以这不一定是最好的解决方案,但它很有效

import tkinter as tk

root = tk.Tk()

frame1 = tk.Frame(root)
frame1.pack(side=tk.TOP, fill=tk.X)
liste_boutton = ['3DS','DS','GB']
button = list()
photo = list()
for num,button_name in enumerate(liste_boutton):
    button.append(tk.Button(frame1))
    photo.append(tk.PhotoImage(file=".\dbinb\img\\{}.png".format(button_name)))
    button[-1].config(bg="grey72",image=photo[-1], width="180", height="50")
    button[-1].grid(row=num,column=0)

root.mainloop()

查看有关将图像放置在按钮上的每个问题,无论何时-您必须将图像的引用保留在某个位置,否则它将被垃圾收集。
Button.img=photo
也许。始终添加问题中的错误消息-它总是有用的信息。而且它将更具可读性。我看到
图像“pyimage2”错误中不存在
,因此问题可以被垃圾收集-请参阅第一条评论。阅读说明:在页面底部,您是否尝试使用
按钮。img=photo
?描述问题和解决方案