1

I want my webcam and tkinter running at the same time. i have a code here, but the problem is the video must be terminated before the tkinter appears. Is it possible to run it at the same time?

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
Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
jomsamago
  • 27
  • 1
  • 8
  • 1
    you will most likely need separate threads for gui-management and for video capturing – Dunno Apr 13 '18 at 11:58
  • Since you're operate with a sequence of frames, there's no need in `threading`, which is a blunt overhead in your case. Replace your `while` loop with [`after` loop](https://stackoverflow.com/questions/25753632/tkinter-how-to-use-after-method). – CommonSense Apr 13 '18 at 13:43

1 Answers1

-1

Of course it is possible, as mentioned by @Dunno you need to run them in separate threads. Use threading module.

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
Pratik Kumar
  • 2,211
  • 1
  • 17
  • 41