Tkinter没有将图像绘制到画布上

时间:2019-01-05 21:39:03

标签: python tkinter

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

示例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

1 个答案:

答案 0 :(得分:2)

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

有帮助吗?

修改

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

相关问题