首页 > 解决方案 > 如何解决函数的 tkinter“pyimage4”错误?

问题描述

我正在编写一个应用程序,该应用程序具有从相机捕获的帧并每 15 毫秒将其馈送到窗口的函数,以及从第一个函数获取图像、裁剪图像并将其馈送到单独窗口的另一个函数每 1500 毫秒。这两个功能通过multiprocessing包同时运行

代码是这样的:

# Imports
from multiprocessing import Process 
import tkinter as tk
import PIL.Image, PIL.ImageTk

from .VideoCapture_old import VideoCapture # video feed func
from .Plots import Plots # image crop function

# Application
class App:
    def __init__(self):

        # Initialising live stream window
        self.stream_window = tk.Tk()
        self.live_canvas = tk.Canvas(self.stream_window)
        self.live_canvas.pack()

        # Initialising window for cropped screen
        self.analyse_window = tk.Tk()
        self.crop_canvas = tk.Canvas(self.analyse_window)
        self.crop_canvas.pack()

        # Initialise camera
        self.vid = VideoCapture() #secondary script not shown here

        # Initialise cropping function
        self.plot = Plots() #secondary script not shown here

        # Setting up multiprocessing
        p1 = Process(target=self.update_feed())
        p2 = Process(target=self.update_plots())

        self.stream_window.mainloop()
        self.analyse_window.mainloop()

    def update_feed(self): #updates the live stream window
        frame = self.vid.get_frame() #gets frame video object
        self.photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(frame)
        self.live_canvas.create_image(0, 0, image = self.photo, anchor = tk.NW)
        self.stream_window.after(15, self.update_feed) #15 ms delay

    def update_plots(self): #updates the crop image window
        cropFrame = self.plot(self.vid.get_frame()) #gets frame from video object and crops the frame
        cropFrame_img = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(cropFrame)
        self.canvas_color.create_image(0, 0, image = cropFrame_img, anchor = tk.NW)
        self.stream_window.after(1500, self.update_plots) #1500 ms delay

当我创建应用程序对象时;有效地运行上面的代码,我得到以下错误。

  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 2293, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "pyimage4" doesn't exist

我知道这是由于 tkinter 无法正确处理照片而导致的错误。effbot建议的解决方案需要使用标签和附加引用,以便 python 不会删除图像。

对于这种特定情况,我应该如何创建额外的参考?

标签: pythontkinter

解决方案


推荐阅读