I have question about how to call some variables, in this case from the method inside exportCsv that belongs to back_Gui class. I want to use the variables self.msg_ and self.opstat in the method __update from class _Gui to stop the reproduction of the gift and promt out the window to save the file. When I run the code and press the button it iterates in an infinite loop because the variable is not passing to. Also, I try to aggregate some threading to not to freeze the window when the button is pressed. Any solution?.
Also, I think these variables I mention would be inside the try but what happens in the except?. Do I have to create more variables to avoid infinite looping on the gift?
from tkinter import *
import tkinter as tk
from tkinter import filedialog
import sqlite3
import pandas as pd
from PIL import Image, ImageTk
import time
import threading
class back_Gui: #Superclass
'''Class that handle the data'''
def __init__(self, db_name = 'database.db'):
self.db_name = db_name
self.msg_ = None
self.opstat = None
.
.
.
def exportCSV(self):
df_to = self.df
try:
export_file = filedialog.asksaveasfilename(defaultextension='.csv')
df_to.to_csv(export_file, index=False, header=True)
except:
pass
#These are the variables that I need
self.msg_ = "Done."
self.opstat = -1
class _Gui(back_Gui): #Subclass
def __init__(self, window):
'''Gui of the windw tk '''
self.wind = window #child
super().__init__()
self.text_font = ('Helvetica', '10', 'bold')
self.Button_(self.wind)
def Button_(self, wind):
"""Run the gift while the csv is being generated"""
#Button
b1 = Button(self.wind, text="random",
font=self.text_font,
command=self.job_genCsv,
).grid(row=1, column=5, padx=5, pady=5 ,sticky=W)
def frame_maps(self, wind):
'''Frame Containter'''
self.frame = LabelFrame(self.wind, text='Hail Hydra', font=self.text_font, height = 500, width = 1300, bd=4)
self.frame.grid(row=2, columnspan=20, sticky=W+E)#, columnspan=3, padx=25, pady=25)
# create the canvas, size in pixels
self.canvas = Canvas(self.frame, width=1300, height=500, bg='white')
# pack the canvas into a frame/form
self.canvas.grid(row=0, columnspan=20, sticky=N, ipadx=20, ipady=20)#
# load the .gif image file
#Here it has to be use the self because is local variable
self.current_image_number = 0
file="cain.gif"
info = Image.open(file)
self.frames = info.n_frames
self.gif1 = [PhotoImage(file=file, format=f"gif -index {i}") for i in range(self.frames)]
def __update(self):
#self.job_genCsv()
''' update the gift '''
self.frame.update_idletasks()#update
if self.opstat >= 0.0:
#msg = self.image_on_canvas #
# next image
self.current_image_number += 1
# return to first image
if self.current_image_number == self.frames: #len(self.images):
self.current_image_number = 0
# change image on canvas
self.canvas.itemconfig(self.update, image=self.gif1[self.current_image_number])
_ = threading.Timer(0, self.__update).start()
print("loop")
else:
if self.msg_ == "Done.":
self.update = self.canvas.create_image(250, 50, anchor=NW, image=self.gif1[self.current_image_number])
del self.msg_
#control variable restablished
self.opstat = 0
print("ends")
def job_genCsv(self):
'''Runs his job and call frame_maps '''
self.frame_maps(self)
_ = threading.Timer(0, self.exportCSV).start()
_ = threading.Timer(0, self.__update).start()
if __name__ == '__main__':
window = Tk()
application = _Gui(window)
window.mainloop()
I'm getting this error:
File "C:\Users\Documents\run.py", line 214, in __update
if self.opstat >= 0.0:
AttributeError: '_Gui' object has no attribute 'opstat'
Related
these two scripts worked fine seperatly and after many differant approches i have got the page1 to open menu_func however when i close menu_func the window remains but deletes the photos etc?
i want the back command to return to the page1 script
i also get this error,
invalid command name "36335088time_now"
while executing
"36335088time_now"
("after" script)
not related to my actual problem but if anybody knows how to get rid of it help would be appreciated
1.page1 code
import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk
from time import strftime
import subprocess
import menu_func
page1 = tk.Toplevel()
width_value=page1.winfo_screenwidth()
height_value=page1.winfo_screenheight()
page1.geometry('%dx%d-0+0' % (width_value, height_value))
page1.resizable(False, False)
BG1_img = Image.open('BG-BLK-1.png')
BG2_img = BG1_img.resize((width_value,height_value))
BG3_img = ImageTk.PhotoImage(BG2_img)
canvas = Canvas(page1)
canvas.pack(expand=True, fill=tk.BOTH)
limg = Label(canvas, i=BG3_img)
limg.pack()
SD1_img = Image.open('Bshut.png')
SD2_img = ImageTk.PhotoImage(SD1_img)
MU1_img = Image.open('./LIST.png')
MU2_img = ImageTk.PhotoImage(MU1_img)
def close():
page1.destroy()
#def MU_COMM():
# import menu_func.py
# page1.exit()
# exec(open('menu_func.py').read())
def time_now():
T_D = strftime('%A, %d %h %Y %H:%M:%S')
show_date.config(text = T_D)
show_date.after(1000, time_now)
exit_button = Button(canvas,image=SD2_img,
command=close,borderwidth='0',border='0',bg='#000000', highlightthickness='0')
exit_button.place(x=1700, y=900)
show_date = Label(canvas, font="Calibri, 46", fg="red", border='0',bg='#00090e')
show_date.place(x=440, y=960)
menu_button = Button(canvas, image=MU2_img, command= menu_func.menu, borderwidth=0,
bg='#000000', highlightthickness=0)
menu_button.place(x=50, y=900)
time_now()
page1.wm_attributes('-fullscreen', 'True')
page1.mainloop()
2.menu_func code
import tkinter as tk
from tkinter import *
from tkinter.messagebox import showinfo
from PIL import Image, ImageTk
from time import strftime
def menu():
pageM = tk.Toplevel()
w_v=pageM.winfo_screenwidth()
h_v=pageM.winfo_screenheight()
pageM.geometry('%dx%d-0+0' % (w_v, h_v))
pageM.resizable(False, False)
BG1m_img = Image.open('BG-BLK-1.png')
BG2m_img = BG1m_img.resize((w_v,h_v))
BG3m_img = ImageTk.PhotoImage(BG2m_img)
canvas = Canvas(pageM)
butt_W = int(w_v/28)
butt_H = int(h_v/31)
img_W = int(w_v/8)
img_H = int(h_v/4)
canvas = Canvas(pageM)
canvas.pack(expand=True, fill=tk.BOTH)
limg = Label(canvas, i=BG3m_img)
limg.pack()
def time_now():
T_D = strftime('%H:%M:%S')
show_time.config(text = T_D)
show_time.after(1000, time_now)
show_time = Label(canvas, font="Calibri, 46", fg="red", border='0',bg='#003a52')
show_time.place(x=int(w_v/2.3), y=int(h_v/50))
def call_COM():
showinfo(title='Information',message='phone Button clicked!')
call_img = Image.open('CALL.png')
cal1_img = call_img.resize((img_W,img_H))
cal2_img = ImageTk.PhotoImage(cal1_img)
button1=tk.Button(canvas, image=(cal2_img),borderwidth=0,bg='#000000', highlightthickness=0)
button1.place(x=int(w_v/5*1-(img_W)+50),y=int(h_v/3*0.8-(img_H/2)))
def map_COM():
exec(open("mapscreen.py").read())
c1_img = Image.open('comp.png')
c2_img = c1_img.resize((img_W,img_H))
c3_img = ImageTk.PhotoImage(c2_img)
button2=tk.Button(canvas, image=c3_img,command=map_COM,borderwidth=0,bg='#000000', highlightthickness=0)
button2.place(x=int(w_v/5*2-(img_W/1.2)+50),y=int(h_v/3*0.8-(img_H/2)))
def user_COM():
showinfo(title='Information',message='user Button clicked!')
u1_img = Image.open('user.png')
u2_img = u1_img.resize((img_W,img_H))
u3_img = ImageTk.PhotoImage(u2_img)
button3=tk.Button(canvas, image=u3_img,borderwidth=0,bg='#000000', highlightthickness=0)
button3.place(x=int(w_v/5*3-(img_W/1.5)+50),y=int(h_v/3*0.8-(img_H/2)))
def set_COM():
showinfo(title='Information',message='settings Button clicked!')
s1_img = Image.open('settings.png')
s2_img = s1_img.resize((img_W,img_H))
s3_img = ImageTk.PhotoImage(s2_img)
button4=tk.Button(canvas, image=s3_img,borderwidth=0,bg='#000000', highlightthickness=0)
button4.place(x=int(w_v/5*4-(img_W/2)+50),y=int(h_v/3*0.8-(img_H/2)))
def bro_COM():
exec(open('browser.py').read())
b1_img = Image.open('brows.png')
b2_img = b1_img.resize((img_W,img_H))
b3_img = ImageTk.PhotoImage(b2_img)
button5=tk.Button(canvas, image=b3_img,command=bro_COM,borderwidth=0,bg='#000000', highlightthickness=0)
button5.place(x=int(w_v/5*1-(img_W)+50),y=int(h_v/3*2.2-(img_H/1.5)))
def mus_COM():
showinfo(title='Information',message='Music Button clicked!')
m1_img = Image.open('music.png')
m2_img = m1_img.resize((img_W,img_H))
m3_img = ImageTk.PhotoImage(m2_img)
button6=tk.Button(canvas, image=m3_img,borderwidth=0,bg='#000000', highlightthickness=0)
button6.place(x=int(w_v/5*2-(img_W/1.2)+50),y=int(h_v/3*2.2-(img_H/1.5)))
def lite_COMM():
showinfo(title='Information',message='hardware Button clicked!')
t1_img = Image.open('Torch.png')
t2_img = t1_img.resize((img_W,img_H))
t3_img = ImageTk.PhotoImage(t2_img)
button7=tk.Button(canvas, image=t3_img,borderwidth=0,bg='#000000', highlightthickness=0)
button7.place(x=int(w_v/5*3-(img_W/1.5)+50),y=int(h_v/3*2.2-(img_H/1.5)))
def back_COM():
pageM.quit()
# exec(open('start_screen.py').read())
SD1_img = Image.open('home.png')
SD2_img = SD1_img.resize((img_W,img_H))
SD3_img = ImageTk.PhotoImage(SD2_img)
button8=tk.Button(canvas, image=SD3_img,command=back_COM,borderwidth=0,bg='#000000', highlightthickness=0)
button8.place(x=int(w_v/5*4-(img_W/2)+50),y=int(h_v/3*2.2-(img_H/1.5)))
time_now()
print(w_v/5*4-(img_W/2))
print(w_v/5*1-(img_W))
print(img_W)
print(h_v)
print(w_v)
pageM.mainloop()
the print(variables) arnt really part of the script there just there to help me work out locations of widgets!
i also understand this is a long code, if anybody know a way to make it shorter or more efficient please let me know, im not a programmer
thanks
I was trying to make an image slideshow program with Tkinter and Python3. No errors, but not showing the images that are inside my chosen directory. The other libraries that I have use are: PIL, random and glob. Your help will be greatly appreciated.
My system:
Ubuntu 20.04 LTS
Here is the code:
import tkinter as Tk
from PIL import Image, ImageTk
import random
import glob
class gui:
def __init__(self, mainwin):
self.counter = 0
self.mainwin = mainwin
self.mainwin.title("Our Photos")
self.colour()
self.mainwin.configure(bg = "yellow")
self.Frame = Tk.Frame(mainwin)
self.img = Tk.Label(self.Frame)
self.Frame.place(relheight = 0.85, relwidth = 0.9, relx = 0.05, rely = 0.05 )
self.img.pack()
self.pic()
def colour(self):
self.colours =['gray47','gray48']
c = random.choice(self.colours)
self.mainwin.configure(bg = c)
root.after(4000, self.colour)
def pic(self):
for name in glob.glob(r"/home/maheswar/Pictures/*"):
self.pic_list = []
val = name
self.pic_list.append(val)
if self.counter == len(self.pic_list) - 1:
self.counter = 0
else:
self.counter == self.counter + 1
self.file = self.pic_list[self.counter]
self.load = Image.open(self.file)
self.pic_width = self.load.size[0]
self.pic_height = self.load.size[1]
self.real_aspect = self.pic_width/self.pic_height
self.calc_width = int(self.real_aspect * 800)
self.load2 = self.load.resize((self.calc_width, 800))
self.render = ImageTk.PhotoImage(self.load2)
self.img.config(image = self.render)
self.img.image = self.render
root.after(2000, self.pic)
root = Tk.Tk()
myprog = gui(root)
root.geometry("1000x1000")
root.mainloop()
I found two mistaces - which probably you could see if you would use print() to debug code
First: you create list self.pic_list = [] inside loop so you replace previous content and this way you can get only one list. But you don't event need this loop but directly
self.pic_list = glob.glob(r"/home/maheswar/Pictures/*")
Second: you need = instead of == in line self.counter = self.counter + 1 or even simpler
self.counter += 1
Full working code with small changes.
import tkinter as Tk
from PIL import Image, ImageTk
import random
import glob
class GUI: # PEP8: `CamelCaseNames` for classes
def __init__(self, mainwin):
self.mainwin = mainwin
self.mainwin.title("Our Photos")
self.mainwin.configure(bg="yellow") # PEP8: inside `()` use `=` without spaces
self.counter = 0
self.frame = Tk.Frame(mainwin) # PEP8: `lower_case_names` for variables
self.frame.place(relheight=0.85, relwidth=0.9, relx=0.05, rely=0.05)
self.img = Tk.Label(self.frame)
self.img.pack()
self.pic_list = glob.glob("/home/maheswar/Pictures/*") # no need prefix `r`
self.colours = ['gray47', 'gray48'] # PEP8: space after `,`
self.colour()
self.pic()
def colour(self):
selected = random.choice(self.colours)
self.mainwin.configure(bg=selected)
root.after(4000, self.colour)
def pic(self):
filename = self.pic_list[self.counter]
image = Image.open(filename)
real_aspect = image.size[0]/image.size[1]
width = int(real_aspect * 800)
image = image.resize((width, 800))
self.photo = ImageTk.PhotoImage(image)
self.img.config(image=self.photo)
#self.img.image = self.render no need if you use `self.` to keep PhotoImage
self.counter += 1
if self.counter >= len(self.pic_list):
self.counter = 0
root.after(2000, self.pic)
# --- main ---
root = Tk.Tk()
myprog = GUI(root)
root.geometry("1000x1000")
root.mainloop()
PEP 8 -- Style Guide for Python Code
I have made a simple GUI that has two buttons for a Square function and Exit button. I want to print the results on the canvas as shown in the expected results.
Here are my codes
from tkinter import *
from PIL import Image,ImageTk
from tkinter import filedialog
from PIL import Image, ImageTk
import os
import cv2
import numpy as np
import time
class application(Tk):
def __init__(self,parent):
Tk.__init__(self,parent)
self.parent = parent
self.minsize(width=300,height=500)
self.initialize()
def initialize(self):
self.grid_columnconfigure(0,weight=1)
self.grid_columnconfigure(1,weight=1)
self.grid_columnconfigure(2,weight=1)
#Button widgets
###########################################################################################
self.button1 = Button(self,text='Square',bg= 'blue',width=15,height=2, command =Square)
self.button1.grid(column=0,row=1,sticky='W',pady=5)
self.button3 = Button(self,text='Exit',bg= 'blue',width=10,height=2,command=self.destroy)
self.button3.grid(column=1,row=5,sticky='W',pady=5)
#Text widget for inserting the result
############################################################################################
self.canvas = Canvas(self,width=230,height=180,state=NORMAL)
self.canvas.grid(column=0,row=4,sticky='W',padx=100,pady=10)
#self.canvas.configure(bg='green')
#Label widget
############################################################################################
self.label3 = Label(self,text="Square",bg = 'red',width=10,height=2,anchor="center")
self.label3.grid(column=0,row=3,sticky='W',padx=120)
def Square(self):
for i in range(1,10):
y = i**2
print(i, y)
if __name__ == "__main__":
app = application(None)
#font.nametofont('TkDefaultFont').configure(size=10)
app['bg']='red'
app.title("square")
app.mainloop()
My expected results are given in the image below
Not entirely sure what you are asking. But, if you just want to create text on canvas use canvas.create_text(x, y, text).
from tkinter import *
from PIL import Image,ImageTk
class application(Tk):
def __init__(self,parent):
Tk.__init__(self,parent)
self.parent = parent
self.minsize(width=300,height=500)
self.initialize()
def initialize(self):
self.grid_columnconfigure(0,weight=1)
self.grid_columnconfigure(1,weight=1)
self.grid_columnconfigure(2,weight=1)
#Button widgets
###########################################################################################
self.button1 = Button(self,text='Square',bg= 'blue',width=15,height=2, command=self.Square)
self.button1.grid(column=0,row=1,sticky='W',pady=5)
self.button3 = Button(self,text='Exit',bg= 'blue',width=10,height=2,command=self.destroy)
self.button3.grid(column=1,row=5,sticky='W',pady=5)
#Text widget for inserting the result
############################################################################################
self.canvas = Canvas(self,width=230,height=180,state=NORMAL)
self.canvas.grid(column=0,row=4,sticky='W',padx=100,pady=10)
#self.canvas.configure(bg='green')
self.label3 = Label(self,text="Square",bg = 'red',width=10,height=2,anchor="center")
self.label3.grid(column=0,row=3,sticky='W',padx=120)
def Square(self):
for i in range(1,10):
y = i**2
print(i, y)
c_id = self.canvas.create_text(0, 20, text=f"{i}\t{y}", fill="blue", font="Times 14")
bbox = self.canvas.bbox(c_id)
self.canvas.coords(c_id, 100, bbox[3]*i)
if __name__ == "__main__":
app = application(None)
#font.nametofont('TkDefaultFont').configure(size=10)
app['bg']='red'
app.title("square")
app.mainloop()
In the tkinter GUI I created a run Button. I liked to click the button then it should start counting. But When I call the method into the ttk.Button as command. it does not work. In this code two class was created. run method was created in the first class and it will be call into the second class. Could you please kindly check the code. Thanks in advance.
from tkinter import *
import threading
import queue
from time import sleep
import random
from tkinter import ttk
class Thread_0(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
count = 0
while True:
count +=1
hmi.thread_0_update(count)
sleep(random.random()/100)
class HMI:
def __init__(self):
self.master=Tk()
self.master.geometry('200x200+1+1')
self.f=ttk.Frame(self.master,height = 100, width = 100, relief= 'ridge')
self.f.grid(row=1,column=1, padx=20, pady=20)
self.l0=ttk.Label(self.f)
self.l0.grid(row=1,column=1)
self.button=ttk.Button(self.master, text = 'run')
self.button.grid(row=2,column=2)
self.q0=queue.Queue()
self.master.bind("<<Thread_0_Label_Update>>",self.thread_0_update_e)
def start(self):
self.master.mainloop()
self.master.destroy()
#################################
def thread_0_update(self,val):
self.q0.put(val)
self.master.event_generate('<<Thread_0_Label_Update>>',when='tail')
def thread_0_update_e(self,e):
while self.q0.qsize():
try:
val=self.q0.get()
self.l0.config(text=str(val), font = ('Times New Roman', 15))
except queue.Empty:
pass
##########################
if __name__=='__main__':
hmi=HMI()
t0=Thread_0()
t0.start()
hmi.start()
You can use
Button( ..., command=t0.start )
See: start is without (). But you have to create t0 before hmi
if __name__ == '__main__':
t0 = Thread_0()
hmi = HMI()
hmi.start()
Full code which works for me
from tkinter import *
import threading
import queue
from time import sleep
import random
from tkinter import ttk
class Thread_0(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
count = 0
while True:
count +=1
hmi.thread_0_update(count)
sleep(random.random()/100)
class HMI:
def __init__(self):
self.master=Tk()
self.master.geometry('200x200+1+1')
self.f = ttk.Frame(self.master, height=100, width=100, relief='ridge')
self.f.grid(row=1, column=1, padx=20, pady=20)
self.l0 = ttk.Label(self.f)
self.l0.grid(row=1, column=1)
self.button = ttk.Button(self.master, text='run', command=t0.start)
self.button.grid(row=2, column=2)
self.q0 = queue.Queue()
self.master.bind("<<Thread_0_Label_Update>>", self.thread_0_update_e)
def start(self):
self.master.mainloop()
self.master.destroy()
#################################
def thread_0_update(self,val):
self.q0.put(val)
self.master.event_generate('<<Thread_0_Label_Update>>', when='tail')
def thread_0_update_e(self,e):
while self.q0.qsize():
try:
val = self.q0.get()
self.l0.config(text=str(val), font=('Times New Roman', 15))
except queue.Empty:
pass
##########################
if __name__ == '__main__':
t0 = Thread_0()
hmi = HMI()
hmi.start()
My task is to display a webcam stream and its black&white stream in two different frames on a single GUI using Tkinter on python. I have seen some examples on google, but they are of images not videos as in the link here. Example of image display in 2 panes on a single GUI
I need exactly the same thing but for the real time video through my webcam.
Initial question:
"I am having issues in displaying multiple (2) windows for displaying video frames in a GUI using Tkinter in python. Please help me with a
code for this task."
The initial question mentioned 2 windows so here's a basic example on how to create multiple windows with tkinter:
#import tkinter as tk
import Tkinter as tk
class MainWindow(tk.Tk):
def __init__(self, *args, **kwargs):
#super().__init__()
tk.Tk.__init__(self)
self.title("This is the MainWindow")
self._is_hidden = False
self.window1 = OtherWindow(self, title="window 1")
self.window2 = OtherWindow(self, title="window 2")
def toggle_hide(self):
if self._is_hidden:
self.iconify()
self.deiconify()
else:
self.withdraw()
self._is_hidden = not self._is_hidden
class OtherWindow(tk.Toplevel):
def __init__(self, master, *args, **kwargs):
#super().__init__(master)
tk.Toplevel.__init__(self, master)
if 'title' in kwargs:
self.title(kwargs['title'])
self.hide_main_button = tk.Button(self, text="Hide/Show MainWindow")
self.hide_main_button['command'] = self.master.toggle_hide
self.hide_main_button.pack()
if __name__ == '__main__':
root = MainWindow()
root.mainloop()
from ttk import *
import Tkinter as tk
from Tkinter import *
import cv2
from PIL import Image, ImageTk
import os
import numpy as np
global last_frame #creating global variable
last_frame = np.zeros((480, 640, 3), dtype=np.uint8)
global last_frame2 #creating global variable
last_frame2 = np.zeros((480, 640, 3), dtype=np.uint8)
global cap
cap = cv2.VideoCapture(1)
def show_vid(): #creating a function
if not cap.isOpened(): #checks for the opening of camera
print("cant open the camera")
flag, frame = cap.read()
frame = cv2.resize(frame,(400,500))
if flag is None:
print "Major error!"
elif flag:
global last_frame
last_frame = frame.copy()
global last_frame2
last_frame2 = frame.copy()
pic = cv2.cvtColor(last_frame, cv2.COLOR_BGR2RGB) #we can change the display color of the frame gray,black&white here
img = Image.fromarray(pic)
imgtk = ImageTk.PhotoImage(image=img)
lmain.imgtk = imgtk
lmain.configure(image=imgtk)
lmain.after(10, show_vid)
def show_vid2():
pic2 = cv2.cvtColor(last_frame2, cv2.COLOR_BGR2GRAY)
img2 = Image.fromarray(pic2)
img2tk = ImageTk.PhotoImage(image=img2)
lmain2.img2tk = img2tk
lmain2.configure(image=img2tk)
lmain2.after(10, show_vid2)
if __name__ == '__main__':
root=tk.Tk() #assigning root variable for Tkinter as tk
lmain = tk.Label(master=root)
lmain2 = tk.Label(master=root)
#lmain.Frame= Frame(width=768, height=576)
#framex.grid(column=3,rowspan=2,padx=5, pady=5)
lmain.pack(side = LEFT)
lmain2.pack(side = RIGHT)
root.title("Fire Alarm Detector") #you can give any title
root.geometry("900x700+100+10") #size of window , x-axis, yaxis
exitbutton = Button(root, text='Quit',fg="red",command= root.destroy).pack(side = BOTTOM,)
show_vid()
show_vid2()
root.mainloop() #keeps the application in an infinite loop so it works continuosly
cap.release()
import tkinter
import PIL.Image
import PIL.ImageTk
import cv2
class App:
def __init__(self, window, video_source1, video_source2):
self.window = window
self.window.title("KEC MEDIA PLAYER")
self.video_source1 = video_source1
self.video_source2 = video_source2
self.photo1 = ""
self.photo2 = ""
# open video source
self.vid1 = MyVideoCapture(self.video_source1, self.video_source2)
# Create a canvas that can fit the above video source size
self.canvas1 = tkinter.Canvas(window, width=500, height=500)
self.canvas2 = tkinter.Canvas(window, width=500, height=500)
self.canvas1.pack(padx=5, pady=10, side="left")
self.canvas2.pack(padx=5, pady=60, side="left")
# After it is called once, the update method will be automatically called every delay milliseconds
self.delay = 15
self.update()
self.window.mainloop()
def update(self):
# Get a frame from the video source
ret1, frame1, ret2, frame2 = self.vid1.get_frame
if ret1 and ret2:
self.photo1 = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(frame1))
self.photo2 = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(frame2))
self.canvas1.create_image(0, 0, image=self.photo1, anchor=tkinter.NW)
self.canvas2.create_image(0, 0, image=self.photo2, anchor=tkinter.NW)
self.window.after(self.delay, self.update)
class MyVideoCapture:
def __init__(self, video_source1, video_source2):
# Open the video source
self.vid1 = cv2.VideoCapture(video_source1)
self.vid2 = cv2.VideoCapture(video_source2)
if not self.vid1.isOpened():
raise ValueError("Unable to open video source", video_source1)
#property
def get_frame(self):
ret1 = ""
ret2 = ""
if self.vid1.isOpened() and self.vid2.isOpened():
ret1, frame1 = self.vid1.read()
ret2, frame2 = self.vid2.read()
frame1 = cv2.resize(frame1, (500, 500))
frame2 = cv2.resize(frame2, (500, 500))
if ret1 and ret2:
# Return a boolean success flag and the current frame converted to BGR
return ret1, cv2.cvtColor(frame1, cv2.COLOR_BGR2RGB), ret2, cv2.cvtColor(frame2, cv2.COLOR_BGR2RGB)
else:
return ret1, None, ret2, None
else:
return ret1, None, ret2, None
# Release the video source when the object is destroyed
def __del__(self):
if self.vid1.isOpened():
self.vid1.release()
if self.vid2.isOpened():
self.vid2.release()
def callback():
global v1,v2
v1=E1.get()
v2=E2.get()
if v1 == "" or v2 == "":
L3.pack()
return
initial.destroy()
v1 = ""
v2 = ""
initial = tkinter.Tk()
initial.title("KEC MEDIA PLAYER")
L0 = tkinter.Label(initial, text="Enter the full path")
L0.pack()
L1 = tkinter.Label(initial, text="Video 1")
L1.pack()
E1 = tkinter.Entry(initial, bd =5)
E1.pack()
L2 = tkinter.Label(initial, text="Video 2")
L2.pack()
E2 = tkinter.Entry(initial, bd =5)
E2.pack()
B = tkinter.Button(initial, text ="Next", command = callback)
B.pack()
L3 = tkinter.Label(initial, text="Enter both the names")
initial.mainloop()
# Create a window and pass it to the Application object
App(tkinter.Tk(),v1, v2)
This code works under normal circumstances but I haven't handled situations where one video ends and the other is still playing. Also, the audio has not been handled in this code.
I created two canvases in the same window and ran the video as a series of images. I have resized the video to fit a constant canvas size but you can change the canvas size to fit the video if you want.
You can change the source to be from your webcam.