同时运行网络摄像头和tkinter

时间:2018-04-13 11:51:08

标签: python python-3.x tkinter video-capture cv2

我希望我的网络摄像头和tkinter同时运行。我有一个代码,但问题是视频必须在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

1 个答案:

答案 0 :(得分:-1)

当然有可能,正如@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