【问题标题】:How to insert an image using Canvas in Tkinter?如何在 Tkinter 中使用 Canvas 插入图像?
【发布时间】:2018-03-15 20:50:52
【问题描述】:

我正在尝试使用 tkinter 中的 Canvas 在我的 python 应用程序中插入图像。相同的代码是:

class Welcomepage(tk.Frame):

def __init__(self, parent, controller):
    tk.Frame.__init__(self,parent)
    canvas = tk.Canvas(self, width = 1000, height = 1000, bg = 'blue')
    canvas.pack(expand = tk.YES, fill = tk.BOTH)
    image = tk.PhotoImage(file="ice_mix.gif")
    canvas.create_image(480, 258, image = image, anchor = tk.NW)

图像正在从源中读取,但仍未显示在框架中。我是 GUI 编程新手,请帮助我。

【问题讨论】:

  • image 替换为self.imageimage = self.image

标签: python tkinter tkinter-canvas


【解决方案1】:

这里可能的问题是图像被 Python 垃圾收集,因此没有显示 - 这是 @nae 的评论所暗示的。将它附加到 self 引用将阻止它被垃圾收集。

self.image = tk.PhotoImage(file="ice_mix.gif")  # Use self.image
canvas.create_image(480, 258, image = self.image, anchor = tk.NW)

effbot.org 上的Tkinter Book 解释了这一点:

注意:当 Python 对 PhotoImage 对象进行垃圾收集时(例如 当您从将图像存储在本地的函数返回时 变量),图像被清除,即使它正在被 Tkinter 小部件。

为避免这种情况,程序必须保留对图像的额外引用 目的。一种简单的方法是将图像分配给小部件 属性,像这样:

label = Label(image=photo) 
label.image = photo # keep a reference!
label.pack()

【讨论】:

    【解决方案2】:
    1. 如果您仍需要使用 Canvas 而不是 Label 在函数或方法中放置图像,您可以使用外部链接来放置图像,并使用 全局 函数内此链接的说明符。
    2. 您可能需要使用 SE 锚点,而不是 NW。

    此代码成功运行(从 USB 摄像头获取 OpenCV 图像并将其放入 Tkinter Canvas):

    def singleFrame1():
        global imageTK      # declared previously in global area
        global videoPanel1  # also global declaration (initialized as "None")
        videoCapture=cv2.VideoCapture(0)
        success,frame=videoCapture.read()
        videoCapture.release()
        vHeight=frame.shape[0]
        vWidth=frame.shape[1]
        imageRGB=cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)  # OpenCV RGB-image
        imagePIL=Image.fromarray(imageRGB)              # PIL image
        imageTK=ImageTk.PhotoImage(imagePIL)            # Tkinter PhotoImage
        if videoPanel1 is None:
            videoPanel1=Canvas(root,height=vHeight,width=vWidth)  # root - a main Tkinter object
            videoPanel1.create_image(vWidth,vHeight,image=imageTK,anchor=SE)
            videoPanel1.pack()
        else:
            videoPanel1.create_image(vWidth,vHeight,image=imageTK,anchor=SE)
    

    【讨论】:

      猜你喜欢
      • 2021-03-08
      • 2011-06-18
      • 1970-01-01
      • 2020-01-24
      • 2021-04-09
      • 2013-08-24
      • 1970-01-01
      • 2014-08-17
      • 2021-12-05
      相关资源
      最近更新 更多