微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 tkinter 调用计算机摄像头并得到错误:无效的命令名称“.!toplevel.!canvas”

如何解决使用 tkinter 调用计算机摄像头并得到错误:无效的命令名称“.!toplevel.!canvas”

我正在尝试使用 tkinter 调用计算机摄像头并保存图片以供进一步处理。捕获工作正常,我可以成功调用相机并查看自己,但是每次单击“save_pic”按钮时,什么也没有发生,然后我关闭窗口并出现此错误。我一直在尝试搜索类似的问题,但仍然没有得到满意的答案。这真让我抓狂。请帮我解决这个问题。预先非常感谢您!

def shot_pic():
    global flag#use flag to save the picture
    global filename
    flag = 0
    capture = cv2.VideoCapture(0)
    capture.set(cv2.CAP_PROP_FRAME_WIDTH,640) #set the size of bg
    capture.set(cv2.CAP_PROP_FRAME_HEIGHT,480) 

    top = Toplevel()#use toplevel to generate the window because I have a mainnwindow in the main function
    top.title('camera shot')
    frm_top = Frame(top)
    Button(top,height=2,width=8,text='save picture',command=save_pic).pack(side=TOP)
    canvas = Canvas(top,bg='black',height=480,width=640)
    canvas.pack()

    #capture video
    while (capture.isOpened()):
        ret,frame = capture.read() #ret shows that whether I get the video frame
        if ret:
            cv2image = cv2.cvtColor(frame,cv2.COLOR_BGR2RGBA)
            img = Image.fromarray(cv2image)
            image_file = ImageTk.PhotoImage(img)
            canvas.create_image(0,anchor='nw',image=image_file)#draw the picture on the bg
            canvas.image_file = image_file
            frm_top.update_idletasks()
            frm_top.update()

        if flag==1:#save picture
            cv2.imwrite("cut_img.jpg",frame)  
            img = cv2.imread('cut_img.jpg')
            img = img[110:420,180:490]  #set size of pic
            img = cv2.resize(img,(224,224))
            cv2.imwrite("cut_img.jpg",img)  
            filename = "cut_img.jpg"
            break

    capture.release()
    cv2.destroyAllWindows()
    top.destroy()
    pic_name = "cut_img.jpg"
    img1 = Image.open(pic_name)  #return the picture to the mainwindow
    photo1 = ImageTk.PhotoImage(img1)
    img_label1.config(imag=photo1)
    mainloop()
def save_pic():#the button function of save picture
    flag = 1
    return

以及以下错误

Exception in Tkinter callback
Traceback (most recent call last):
  File "E:\miniconda3\envs\gluon\lib\tkinter\__init__.py",line 1705,in __call__
    return self.func(*args)
  File "GUI.py",line 45,in shot_pic
    canvas.create_image(0,image=image_file)
  File "E:\miniconda3\envs\gluon\lib\tkinter\__init__.py",line 2489,in create_image
    return self._create('image',args,kw)
  File "E:\miniconda3\envs\gluon\lib\tkinter\__init__.py",line 2480,in _create
    *(args + self._options(cnf,kw))))
_tkinter.TclError: invalid command name ".!toplevel.!canvas"

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。