0

我正在寻找一种为小游戏生成带有图片的按钮的方法。我以两种方式使用 Tkinter 和 Grid 布局,但只有一种有效。

下面是第一种(硬编码)方式生成带有图片的 Button 的示例代码:

currentImage=PhotoImage(file="Pictures//greenopen1s.gif")
currentImage = currentImage.subsample(x = "2", y = "2")
b2 = Button(root, image=currentImage)
b2.grid(column = 0, row = 1)

root.mainloop()

这是生成按钮的第二种通用​​方法,该按钮根据参数卡打开图像:

b1 = Button(root, image=getImage(visibleCards[0])) 
b1.grid(column = 0, row = 0)

root.mainloop()

def getImage(card):
 currentPath = "Pictures//"
 currentColor = card.color
 currentPath = currentPath + currentColor
 currentShading = card.shading
 currentPath = currentPath + currentShading
 currentNumber = card.number
 currentPath = currentPath + currentNumber
 currentPath = currentPath + card.symbol
 currentPath = currentPath + ".gif"

 currentImage=PhotoImage(file=currentPath)
 currentImage = currentImage.subsample(x = "2", y = "2")

 return currentImage

加载 PhotoImage 的图像算法正常工作,并且 .gif 文件位于正确的位置。我想知道这两种获取图像的方式之间的区别。

非常感谢你

4

1 回答 1

2

PhotoImage垃圾收集有问题,所以任何被设置为PhotoImage对象的变量都不能被垃圾收集。老实说,这有点奇怪,我不确定为什么会这样。


尝试这样的事情:

myImage = getImage(visibleCards[0])
b1 = Button(root, image=myImage) 
b1.grid(column = 0, row = 0)

root.mainloop()

def getImage(card):
    currentPath = "Pictures//"
    currentColor = card.color
    currentPath = currentPath + currentColor
    currentShading = card.shading
    currentPath = currentPath + currentShading
    currentNumber = card.number
    currentPath = currentPath + currentNumber
    currentPath = currentPath + card.symbol
    currentPath = currentPath + ".gif"

    currentImage=PhotoImage(file=currentPath)
    currentImage = currentImage.subsample(x = "2", y = "2")

    return currentImage
于 2014-08-13T22:47:38.040 回答