Home > Net >  How can i open tkinter window and opencv window at the same time?
How can i open tkinter window and opencv window at the same time?

Time:11-07

I want to open tkinter window and opencv window at the same time. Help me pleas to run them at the same time. How can I do that? Here is Code:

import numpy as np
import cv2
from mss import mss
from PIL import Image
import pyautogui
import pyautogui as pg
import tkinter as tk


mon = {'left': 500, 'top': 500, 'width': 500, 'height': 500}

root = tk.Tk()
root.geometry("400x300")
root.title("Tkinter")

root.attributes('-transparentcolor',
                'red')

root.config(bg='red')

root.mainloop()

with mss() as sct:

    while True:

        screenShot = sct.grab(mon)
        img = Image.frombytes(
            'RGB',
            (screenShot.width, screenShot.height),
            screenShot.rgb,
        )
        cv2.imshow('ProjectZero', np.array(img))
        if cv2.waitKey(33) & 0xFF in (
            ord('q'),
            27,
        ):
            break

but everytime I try, happens next:

  1. tkinter window opens and after I close it, opens opencv window. (I need to open them at the same time)
  2. tkinter window and opencv window opens at the same time. But opencv doesnt refresh the window. Only if I spam close button for tkinter window.
  3. Or after closing tkinter window. Opens Opencv window and works properly. But im not able anymore to open tkinter window.

CodePudding user response:

I wrote a mini-code so you can figure it out. My program displays a tkinter window and my webcam window via OpenCV. They run in parallel, and do not interfere with each other's work. I did this thanks to the threading module (it's a built-in python module). This module allows you to run processes in parallel.

from tkinter import *
import cv2
from threading import *

def window_Tk():
    root = Tk()
    root.geometry('200x200')
    btn = Button(root, text='click').pack()
    root.mainloop()

def window_CV():
    cap = cv2.VideoCapture(0)

    while True:
        ret, frame = cap.read()
        cv2.imshow('frame', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        if cv2.getWindowProperty('frame',1) == -1 :
            break
    cap.release()
    cv2.destroyAllWindows()

t1 = Thread(target=window_Tk)
t2 = Thread(target=window_CV)

t1.start()
t2.start()
  • Related