Python 同时运行网络摄像头和tkinter
我希望我的网络摄像头和tkinter同时运行。我这里有一个代码,但问题是视频必须在tkinter出现之前终止。可以同时运行吗Python 同时运行网络摄像头和tkinter,python,python-3.x,tkinter,video-capture,cv2,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
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所提到的,您需要在单独的线程中运行它们。使用线程模块
对于gui管理和视频捕获,您很可能需要单独的线程,因为您使用的是一系列帧,所以不需要线程,这在您的情况下是一种直接的开销。将while循环替换为。
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