首页 > 解决方案 > 使用函数显示图像按钮

问题描述

我想创建很多按钮。所以,我创建了一个函数,我调用这个函数来创建一个按钮。这些按钮有一个图像,所以我在调用函数时在参数上添加了图像的链接。

知道 Tkinter Image 的运行时错误,我使用了一个列表来保存图像链接。

问题是它只显示一个按钮。列表可能有问题?

from tkinter import *
app = Tk()

a = []
i = 0
def CreateButton (file, row):
    global i 
    global ButtonCreationImg
    global a
    a.insert(i, file)
    ButtonCreationImg = PhotoImage(file = a[i])
    ButtonCreation = Button(app, image=ButtonCreationImg, border='0')
    ButtonCreation.grid(row=row, column=0, columnspan=4, ipadx=0)
    i += 1



CreateButton("bouton_1.png", 6)
CreateButton("bouton_2.png", 8)


app.mainloop()

标签: python

解决方案


我预计问题出在错误中PhotoImage,当它在函数中创建并分配给局部变量时,它会从内存中Garbage Collector删除-当它从函数中退出时,它会被删除。PhotoImageGarbage Collector

您可以Note在 effbot.org 上阅读有关此问题的信息:PhotoImage

button.img用来分配PhotoImage给类,所以它会保存在内存中。

我还对代码进行了其他更改,但它们对于这个问题并不重要。

import tkinter as tk
from PIL import ImageTk

# --- functions ---

def create_button(all_files, filename, row):
    all_files.append(filename)
    button_image = ImageTk.PhotoImage(file=all_files[-1])
    button = tk.Button(app, image=button_image, border='0')
    button.img = button_image # solution for bug with PhotoImage
    button.grid(row=row, column=0, columnspan=4, ipadx=0)

# --- main ---

all_files = []

app = tk.Tk()

create_button(all_files, "bouton_1.png", 6)
create_button(all_files, "bouton_2.png", 8)

app.mainloop()

推荐阅读