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/