首页 > 解决方案 > 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 是一个包含一些名称的列表当我在我的窗口中运行代码时,我只得到最后一个按钮(图像)为什么会这样?我正在尝试制作一个循环,将一些按钮放在一起

标签: pythonloopstkinter

解决方案


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

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() 

推荐阅读