pythontkinter按钮只适用于硬编码图像

2024-05-18 15:19:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种方法来生成一个小游戏的图片按钮。 我用了Tkinter和网格布局两种方式,但只有一种有效。在

以下是第一种(硬编码)生成带有图片的按钮的示例代码:

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()

下面是第二种生成按钮的通用方法,该按钮具有根据论证卡打开的图像:

^{pr2}$

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

非常感谢


Tags: 方法图像网格示例编码tkinter方式图片
1条回答
网友
1楼 · 发布于 2024-05-18 15:19:48

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

相关问题 更多 >

    热门问题