在tkinter应用程序中向按钮添加图像的问题

时间:2019-03-04 22:52:12

标签: python image button tkinter

我正在帮助一个小项目,我们想要在商店中添加和取出物品。代码如下:

from tkinter import *
import tkinter

####################
# Variables
eggs = 0
milk = 0
butter = 0
lemon = 0
guiSize = "800x1280"

def newItemGUI():
    main.withdraw()

    def addEgg():
        global eggs
        eggs += 1
        updateLabels()

    def menu():
        global eggs
        update(eggs)
        itemWindow.destroy()
        main.deiconify()

    def updateLabels():
        eggLabel = Label(itemWindow, text = eggs)
        eggLabel.grid(row = 3,column = 0)

    itemWindow = Toplevel()
    itemWindow.geometry(guiSize)
    itemWindow.title("Add a new item")
    itemWindow.configure(background = "#a1dbcd")

    heading = Label(itemWindow, text="Add new items", font=("Arial",20),background = "#a1dbcd")
    heading.grid(row=0, columnspan = 3)

    egg = PhotoImage(file ="images/egg.gif")
    eggButton = Button(itemWindow, image = egg, command = addEgg)
    eggButton.grid(row = 2, column = 0,padx = 10, pady = 10)
    eggLabel = Label(itemWindow, text = eggs).grid(row = 3,column = 0)

    back = Button(itemWindow, text = "Main Menu", command = menu, width = 15)
    back.grid(row = 4, column = 0, padx = 20, pady = 20)

def update(eggs):

    items.delete("1.0",END)
    items.insert(END,"Eggs \t:")
    items.insert(END,eggs)
    items.insert(END,"\n")

main=tkinter.Tk()
main.geometry(guiSize)
bgColour = "#DDA0DD"
main.configure(background = bgColour)

button1 = Button(main, text="Input new products", width = 20, height = 5, command = newItemGUI)
button1.grid(column = 1, row =2, padx = 20, pady = 20)
label2 = Label(main,text = "Items in the fridge :", font =("Arial,20"), background = bgColour)
label2.grid(row=4, columnspan = 2)
items = Text(main, width = 60, height = 10)

items.insert(END,"Eggs \t:")
items.insert(END,eggs)
items.insert(END,"\n")
items.grid(row=5, columnspan = 4)

main.mainloop()

no image displayed

当您单击输入新产品按钮时,将带您进入新屏幕。屏幕上应该是鸡蛋的照片,下面有一个计数。由于某种原因,鸡蛋的图像没有显示,并且按钮也没有单击。

如果我将eggButton从图像更改为:

eggButton = Button(itemWindow, text = "egg", command = addEgg)

button working with text

这似乎允许我单击并单击变量,并且变量增加了。关于我们哪里/哪里出了问题的任何想法吗?我知道该路径是正确的,因为我可以通过该按钮在Label中显示鸡蛋的图片。

1 个答案:

答案 0 :(得分:0)

问题是因为PhotoImage被存储在egg函数本地的名为newItemGUI()的变量中,所以当该变量(和相关的图像对象)被删除时,函数返回。这是一个相当普遍的问题,因此您的问题很可能是另一个问题的重复项(并可能被关闭)。

PhotoImage documentation提到了避免出现这种潜在问题的方式,如下面结尾处的注释所示。

无论如何,为防止这种情况发生,您可以将值存储在其他地方,例如Toplevel窗口的属性中。我还建议将其名称更改为更具描述性的名称,例如egg_image

这是您的代码更改,显示了如何完成操作:

    itemWindow.egg_image = PhotoImage(file="images/egg.gif")
    eggButton = Button(itemWindow, image=itemWindow.egg_image, command = addEgg)