Python OpenCV output on Tkinter label deletion -
i trying delete tkinter label displaying webcam stream made opencv. made happen not way wanted because stops stream last image outputted stream still present. code this:
from tkinter import * import cv2 pil import image, imagetk def start(): width, height = 800, 600 cap = cv2.videocapture(0) cap.set(cv2.cv.cv_cap_prop_frame_width, width) cap.set(cv2.cv.cv_cap_prop_frame_height, height) def show_frame(): _, frame = cap.read() frame = cv2.flip(frame, 1) cv2image = cv2.cvtcolor(frame, cv2.color_bgr2rgba) img = image.fromarray(cv2image) imgtk = imagetk.photoimage(image=img) lmain.imgtk = imgtk lmain.configure(image=imgtk) lmain.after(10, show_frame) show_frame() root = tk() lmain = label(root) lmain.pack(side = right) button1 = button(root, text = "start", command = start) button1.pack(side = left) button2 = button(root, text = "stop", command = start) button2.pack(side = left) root.mainloop()
you may notice function used stop same function used start it, because clueless on how stop it.
i have tried code, , add code here:
from tkinter import * import cv2 pil import image, imagetk isrunning = 0 def start(): global isrunning if isrunning == 0: width, height = 800, 600 cap = cv2.videocapture(0) cap.set(cv2.cv.cv_cap_prop_frame_width, width) cap.set(cv2.cv.cv_cap_prop_frame_height, height) isrunning = 1 lmain.pack(side = right) def show_frame(): _, frame = cap.read() frame = cv2.flip(frame, 1) cv2image = cv2.cvtcolor(frame, cv2.color_bgr2rgba) img = image.fromarray(cv2image) imgtk = imagetk.photoimage(image=img) lmain.imgtk = imgtk lmain.configure(image=imgtk) if isrunning == 1: lmain.after(10, show_frame) show_frame() def stop(): global isrunning isrunning = 0 lmain.pack_forget() root = tk() lmain = label(root) button1 = button(root, text = "start", command = start) button1.pack(side = left) button2 = button(root, text = "stop", command = stop) button2.pack(side = left) root.mainloop()
you can find add global variable isrunning
let function show_frame
check every time. if variable isrunning
equal 0, function stop. , add function stop
callback function of "stop" button contains code lmain.pack_forget()
remove label.
since label removed every time when click "stop" button, move code adding label start
function. hope helps.
Comments
Post a Comment