python - 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()
推荐阅读
- ios - 使用 RxSwift 的 API 函数
- assembly - 如何正确输入字符串并输出?
- javascript - 使用 if 和 else 检查 for 循环中的所有值
- angular - 在ngrx效果中嵌套管道需要什么?
- c# - 无法使用 List 手动创建 Lambda 表达式树
- python - Django ORM:如何对一个值进行分组并获取该组中最后一个元素的不同值
- python - ValueError:使用序列设置数组元素。如何将我的功能重新排列到 np.arrays?
- java - 转换为泛型类型并调用 doubleValue() 方法
- javascript - 将 innerHTML 切换为不同的值 onclick()
- python - PYTHON:在文本文件中搜索一个单词,其中包含单词之间的空格