tkinter如何循环按钮


for i in champs:

img  = tkinter.PhotoImage(file = r"D:Στοιχεια Ληψης{}.png".format(i))
l1 = tkinter.Label(text=i,bg=bgcolour,fg="White",font = (("Courier", 15)))
l1.place(x= xaxes,y=270)
xaxes = xaxes + 200

button = tkinter.Button(bg=bgcolour,text=i ,image =img, bd="0",     
activebackground = "#00003f", height = "200", width = "200")
button.place(x = x1, y = 60)
x1 = x1 + 100   

Champs是一个包含一些名称的列表当我在窗口中运行代码时,我只得到最后一个按钮(图像(为什么?我正试图做一个循环,把一些按钮放在另一个旁边

您的图像正在被垃圾收集。这里有一个解决方案。

import ntpath
import tkinter as tk
from PIL import Image, ImageTk
root = tk.Tk()
root.geometry("800x600")
#for storing image references
images   = dict()
#list of your image paths
pathlist = ['D:image1.png', 'D:image2.png']
#load paths and save references
for path in pathlist:
name         = ntpath.basename(path).split('.')[0]
images[name] = ImageTk.PhotoImage(Image.open(path), name=name)

#you can assign an image with just the name
labela = tk.Label(root, image='image1')
labela.grid()
#or directly through the images reference
labelb = tk.Label(root, image=images['image2'])
labelb.grid()
root.mainloop() 

最新更新