python - Tkinter 未将图像绘制到 Canvas 上

标签 python tkinter

Tkinter 不会通过其他方法将图像绘制到 Canvas 。

示例 1 有效,示例 2 无效。有人可以解释一下为什么吗?

示例 1

def init_gui(self):
    window = tkinter.Tk()
    self.canvas = tkinter.Canvas(self.window, width=1000, height=500)

    photo = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(self.img))
    self.canvas.create_image(0, 0, image=photo, anchor=tkinter.NW)
    self.canvas.pack()

    window.mainloop()
    pass

示例 2

def init_gui(self):
    window = tkinter.Tk()
    self.canvas = tkinter.Canvas(self.window, width=1000, height=500)

    self._draw_img() # the exact same code, only in another method

    window.mainloop()
    pass
def _draw_img(self):
    photo = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(self.img))
    self.canvas.create_image(0, 0, image=photo, anchor=tkinter.NW)
    self.canvas.pack()
    pass

最佳答案

如果我没记错的话,当您显示的图像超出范围时(因为它是局部变量),Tkinter 中就会出现问题。尝试使 photo 成为类的属性(通过在 _draw_image 函数中将 photo 替换为 self.photo )看看是否可以解决问题。

这有帮助吗?

编辑

有关更完整的说明,请参阅此网站:http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm

关于python - Tkinter 未将图像绘制到 Canvas 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54056512/

相关文章:

python - Jupyter : The kernel appears to have died. 会自动重启。 (喀拉斯相关)

python - 性能考虑 pandas concat 附加

python - 如何绑定(bind)到 Tkinter 中的所有数字键?

python-3.x - 是否可以对 tkinter 进行多进程处理?

Python Tkinter : How to disable window showing in taskbar?

python - 如何在 VSCode 中加载 Python 交互窗口时运行启动命令

python - 为什么 python zipfile 模块比 C 快?

python - 多核批处理

python - 如何获取实例的名称来影响 tkinter 标签

python - 多行 Tkinter 按钮?