带图像的简单GUI [英] Simple GUI with images
问题描述
我正在尝试在我的简单GUI上显示一些卡片,但它没有显示出来。
I'm trying to display some cards on my simple GUI, but it's not showing up.
我上传了一个包含我要上传的.gif的工作文件,代码很接近但不对。
http://www.filedropper.com/cardgameproblem 大小:0Kb,类型:.zip
I've uploaded a working file with the .gif I want to upload, and the code is close but not right. http://www.filedropper.com/cardgameproblem Size: 0Kb, Type:.zip
- 包含1 .py和1 .gif
要看的线路从257-266开始。我知道这只是一个小错误,但我看不到它。
The lines to look at start at 257-266. I know it's just a minor error, but I can't see it.
请帮助
推荐答案
经过一些修补,我发现当存储在GUI的变量中时图像被正确显示,即使用 self
After some tinkering, I found out that the image is properly displayed when stored in a variable of the GUI, i.e. using self
self.gif1 = PhotoImage(file='1.gif')
self.canvas.create_image(0, 0, image=self.gif1, anchor=NW)
我不明白为什么,但这是有效的,而命名变量只需 gif1
(或任何其他名称),而不是 self
,则不然。在您的代码和最小示例中都进行了测试。
I have no idea why, but This works, while naming the variable just gif1
(or any other name), without self
, does not. Tested both in your code and in a minimum example.
更新:正如@Bryan指出的,垃圾收集器处理 PhotoImage
当 __ init __
完成时的实例。您必须保留对构造函数范围之外的实例的引用,例如使用 self
或 global
。鉴于手头的问题,最好创建一个 dict
,使用卡片的名称作为键存储图像。
Update: As @Bryan pointed out, the garbage collector disposes the PhotoImage
instance when __init__
finishes. You have to keep a reference to the instance beyond the scope of the constructor, e.g. using self
, or global
. Given the problem at hand, it might be best to create a dict
, storing the images using the names of the cards as keys.
这篇关于带图像的简单GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!