运行 同时使用网络摄像头和 tkinter

Running webcam and tkinter at the same time

我想要同时使用网络摄像头和 tkinter 运行ning。我这里有一个代码,但问题是视频必须在 tkinter 出现之前终止。可以同时运行吗?

from tkinter import *
import cv2
import tkinter as tk

ui = Tk()
ui.state('zoomed')
canvas = tk.Canvas()
canvas.pack(fill = 'both', expand = True)
video = cv2.VideoCapture(0)
a = 0
while True:
    a+= 1
    check, frame = video.read()
    cv2.imshow('Video', frame)
    key = cv2.waitKey(1)
    if key == 27:
        break
    video.release()
    cv2.destroyAllWindows

当然有可能,正如@Dunno 所提到的,您需要 运行 它们在单独的线程中。使用 线程 模块。

from tkinter import *
import cv2
import tkinter as tk
import threading

ui = Tk()
ui.state('normal')
canvas = tk.Canvas()
canvas.pack(fill = 'both', expand = True)


def video_stream():
  video = cv2.VideoCapture(0)
  a = 0
  while True:
    a+= 1
    check, frame = video.read()
    cv2.imshow('Video', frame)
    key = cv2.waitKey(1)
    if key == 27:
        break
  video.release()
  cv2.destroyAllWindows

th= threading.Thread(target=video_stream) #initialise the thread
th.setDaemon(True)
th.start() #start the thread

ui.mainloop() #Run your UI