如何在Tkinter中使用画布插入图像?

2024-10-02 02:28:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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)

图像正在从源代码读取,但仍没有显示在框架中。我是新的图形用户界面编程有人请帮助我。在


Tags: 代码图像imageself应用程序inittkinterdef
2条回答
  1. 如果您仍然需要使用画布而不是标签来放置函数或方法中的图像,则可以为图像使用外部链接,并为函数内的此链接使用全局规范。在
  2. 您可能需要使用SE锚定,而不是NW。在

此代码成功地工作(从USB摄像头获取OpenCV图像并将其放在Tkinter画布中):

def singleFrame1():
    global imageTK      # declared previously in global area
    global videoPanel1  # also global declaration (declared 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)

这里可能存在的问题是,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)

上的Tkinter Bookeffbot.org网站解释如下:

Note: When a PhotoImage object is garbage-collected by Python (e.g. when you return from a function which stored an image in a local variable), the image is cleared even if it’s being displayed by a Tkinter widget.

To avoid this, the program must keep an extra reference to the image object. A simple way to do this is to assign the image to a widget attribute, like this:

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

相关问题 更多 >

    热门问题