Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 图像未显示在tkinter画布上 在能够复制te问题后更新_Python_Canvas_Tkinter - Fatal编程技术网

Python 图像未显示在tkinter画布上 在能够复制te问题后更新

Python 图像未显示在tkinter画布上 在能够复制te问题后更新,python,canvas,tkinter,Python,Canvas,Tkinter,起初,我可以通过将一个键绑定到画布上使其工作,我不知道为什么这样做有效,但后来它也停止了工作,所以我进一步研究 在设置了一些测试之后,我设法编写了一个简短的代码来复制问题: from tkinter import * class SomeClass: def __init__(self, master): self.can = Canvas(master, bg="gray") self.can.pack() thing = Phot

起初,我可以通过将一个键绑定到画布上使其工作,我不知道为什么这样做有效,但后来它也停止了工作,所以我进一步研究

在设置了一些测试之后,我设法编写了一个简短的代码来复制问题:

from tkinter import *


class SomeClass:
    def __init__(self, master):
        self.can = Canvas(master, bg="gray")
        self.can.pack()

        thing = PhotoImage(file=("./img/thing.PNG"))

        img = self.can.create_image(20, 20, image=thing)

        stuff = self.can.find_all()
        print(stuff)


app = Tk()

SomeClass(app)  # Does not work

something = SomeClass(app)  # Dos not work

# This part does work:
can = Canvas(app, bg="gray")
can.pack()
thing = PhotoImage(file=("./img/thing.PNG"))

img = can.create_image(20, 20, image=thing)

stuff = can.find_all()
print(stuff)

app.mainloop()
在所有情况下,img都会在find_all()中显示为一项,但前两项不会显示在画布上

还尝试将图像的创建作为一种方法,并使用绑定来激活它,认为它在init部分出错。这并没有改变任何事情


那么,我到底做错了什么呢?

所以,在我终于发现问题所在的时候,我回答了自己的问题

我没有阅读有关PhotoImage的文档中的这一行:

必须在Python程序中保留对image对象的引用,方法是将其存储在全局变量中,或将其附加到另一个对象

因此,在这种情况下,使其工作的方法是:

app = Tk()
thing = PhotoImage(file=("./img/thing.PNG")) # making it a global variable


希望这对遇到此问题的其他人有所帮助。

尝试将
Timeline()
的实例分配给变量,如
Timeline=Timeline(frame)
。尝试过后,无效。我设法制作了一个简短的代码来复制这个问题,但是,请参见上面更新的问题。对于更新的代码,请在SomeClass中将
thing=…
更改为
self.thing=…
。同样的情况也会发生,但刚刚找到了答案,图像正在被垃圾收集,我只需要使图像要么是全局的,要么是附加到某个东西上。
class SomeClass:
    def __init__(self, master):
        self.can = Canvas(master, bg="gray")
        thing = PhotoImage(file=("./img/thing.PNG")
        self.can.img = thing   # This attaches the image to the canvas object