python - 使用函数显示图像按钮
问题描述
我想创建很多按钮。所以,我创建了一个函数,我调用这个函数来创建一个按钮。这些按钮有一个图像,所以我在调用函数时在参数上添加了图像的链接。
知道 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()
解决方案
我预计问题出在错误中PhotoImage
,当它在函数中创建并分配给局部变量时,它会从内存中Garbage Collector
删除-当它从函数中退出时,它会被删除。PhotoImage
Garbage 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()
推荐阅读
- node.js - 如何在 async.queue 中使用类变量
- java - 热插拔代理和 DCEVM 的 Jboss JVM 参数配置
- node.js - Nodejs 日期对象到 protobuf
- c++ - 由于 sh.exe 在路径上,在 VSTS Windows 主机上生成 CMake 项目失败
- extjs - Shopware - Extjs - 无法从插件配置窗口发送 Ajax 请求
- ruby - 如何将Ruby字符串编码转换为win32并返回
- java - 用 null 检查 java 变量时哪个更有效?
- powershell - 使用 PowerShell 更改电源计划
- html - 如何获得带圆角的边框底线
- sql - SQL删除重复项,仅保留其他列中具有最小值的记录