【问题标题】:Tkinter - create buttons and its images using loopTkinter - 使用循环创建按钮及其图像
【发布时间】:2020-08-20 09:07:54
【问题描述】:

有没有办法使用循环创建每个具有唯一图像和身份的按钮?我想出了下面的代码,但唯一有效的按钮是最后一个:

import tkinter as tk
from tkinter import *
from functools import partial

win = tk.Tk()
win.geometry('800x500')  # set window size

dic = {0: {"row": 0, "col": 0 }, 1: {"row": 1, "col": 0 }, 2: {"row": 2, "col": 0 }}

chairImg, chair2Img, checkImg = None, None, None

fileList = [chairImg, chair2Img, checkImg]
imgList = ['chair.png', 'chair2.png', 'check.png']
buttonIdentities = []
i=0

def checkButton(n):
    # function to get the index and the identity (bname)
    print(n)
    bname = (buttonIdentities[n])

for img, f in zip(imgList, fileList):
    f = PhotoImage(file=img)
    f = f.zoom(16).subsample(256)
    
    button = Button(win, image=f, command=partial(checkButton, i))
    button.grid(row=dic[i]['row'], column=dic[i]['col'])
    buttonIdentities.append(button)
    i+=1   

print(button_identities)
win.mainloop()

我很想简化我的代码,因为我将在我的应用程序中使用更多按钮和图像。感谢您的时间和回答。

【问题讨论】:

    标签: python-3.x tkinter


    【解决方案1】:

    看起来图像由于垃圾收集而丢失了。 为避免这种情况,只需添加对图像的引用,如下所示:

    button = Button(win, image=f, command=partial(checkButton, i))
    button.image = f #This line here.
    button.grid(row=dic[i]['row'], column=dic[i]['col'])
    

    (不一定是.image,可以是任何东西)
    通过保留对图像的引用,它不会被垃圾收集。你可以阅读更多关于它的信息here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-04
      • 1970-01-01
      • 2020-03-29
      • 1970-01-01
      • 2021-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多