【问题标题】:tkinter how to loop buttonstkinter 如何循环按钮
【发布时间】:2020-08-23 09:09:52
【问题描述】:
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 是一个包含一些名称的列表 当我在我的窗口中运行代码时,我只得到最后一个按钮(图像) 这是为什么? 我正在尝试制作一个循环,将一些按钮放在一起

【问题讨论】:

  • 你需要保留一个参考。 effbot.org/tkinterbook/photoimage.htm
  • 即使在标签中使用图像也会被垃圾收集。将它们存储在范围内的某个列表中。
  • 使用after 功能真的很有帮助。
  • 试试button.image = img?
  • tkinter 图像存在一个臭名昭著的问题,即它们在运行后被删除(“垃圾收集”) - 您需要存储对您不同图像的引用,例如在列表或字典中,然后通过该列表/字典访问图像

标签: python loops tkinter


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    • 2018-09-01
    • 2017-01-26
    • 2021-11-11
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多