【问题标题】:Image display on tkinter canvas not workingtkinter 画布上的图像显示不起作用
【发布时间】:2013-12-02 09:45:27
【问题描述】:

我正在尝试编写一个简单的绘图程序,并且我拥有功能齐全的保存和绘图功能,尽管在打开按钮的方法中,msg.create_image 函数没有显示图像。没有错误,只有 GUI 和一个空白的大画布。 这是我在 python 2.7.5 中的代码,其中 PIL 1.1.7 在 Windows 7 64 位上编写,并且在 Windows 和运行 OS X Mountain Lion 10.9 的 Mac 上都能正常运行 PS我为识别道歉......由于将其复制到此帖子,它们可能会关闭。 谢谢

【问题讨论】:

  • 不要为身份问题道歉,但要纠正这一点。

标签: python canvas tkinter


【解决方案1】:

您必须保留对图像 tk_im 的引用,因为一旦函数退出,它就会被垃圾回收。一种方法是将其添加到 Canvas 实例中。

 def opens():
    global img,msg,idraw
    filename = askopenfilename()
    im = Image.open(filename)
    msg.tk_im = ImageTk.PhotoImage(im)              ## <------------
    a=msg.create_image(0,0,image=msg.tk_im)
    idraw=ImageDraw.Draw(im)

【讨论】:

    【解决方案2】:

    如果您在函数中创建 ImageTk.PhotoImage 并将其分配给局部变量,则当您离开该函数时,它会被垃圾收集器销毁。这就是您看不到图像的原因。

    你必须将它分配给全局变量

    tk_im = None
    
    def opens():
        global img,msg,idraw
    
        global tk_im
    
        filename = askopenfilename()
        im = Image.open(filename)
        tk_im = ImageTk.PhotoImage(im)
        a = msg.create_image(0,0,image=tk_im)
        idraw = ImageDraw.Draw(im)
    

    如果您要添加更多图像,您必须记住全局列表中的所有图像。

    tk_im = []
    
    def opens():
        global img,msg,idraw
    
        global tk_im
    
        filename = askopenfilename()
        im = Image.open(filename)
    
        tk_im.append( ImageTk.PhotoImage(im) )
    
        a = msg.create_image(0,0, image=tk_im[-1] )
        idraw = ImageDraw.Draw(im)
    

    【讨论】:

      猜你喜欢
      • 2014-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-26
      • 2021-12-31
      • 1970-01-01
      相关资源
      最近更新 更多