How to show webcam in TkInter Window - Python

How to show webcam in TkInter Window - Python

To display a webcam feed in a Tkinter window using Python, you can use the opencv-python (OpenCV) library to capture video frames from the webcam and then convert these frames to a format that Tkinter can display. Below is an example of how to do this:

Firstly, ensure you have the required packages installed:

pip install opencv-python pip install opencv-python-headless # If you're running on a headless server pip install pillow # For image processing compatible with Tkinter 

Here is a Python script that creates a Tkinter window and displays the webcam feed:

import tkinter as tk from tkinter import Label import cv2 from PIL import Image, ImageTk # Create an instance of TKinter window or frame win = tk.Tk() # Set the size of the window win.geometry("600x400") # Set a title win.title("Webcam in Tkinter") # Open the webcam (use 0 for default webcam, 1 for external, etc.) cap = cv2.VideoCapture(0) def show_frames(): # Get the latest frame and convert into Image cv2image= cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2RGB) img = Image.fromarray(cv2image) # Convert image to PhotoImage imgtk = ImageTk.PhotoImage(image=img) lbl.imgtk = imgtk lbl.configure(image=imgtk) # Repeat after an interval to capture continuously lbl.after(20, show_frames) # Create a Label to capture the Video frames lbl = Label(win) lbl.pack() show_frames() win.mainloop() # Release the video capture object and close the window after exiting the mainloop cap.release() cv2.destroyAllWindows() 

In this script:

  • We create a Tkinter window and a label to hold the video frames.
  • The show_frames function captures frames from the webcam, converts them to a Tkinter-compatible format using PIL, and updates the label with the new frame.
  • We use a Tkinter label widget, lbl, to display the frames.
  • We use lbl.after(20, show_frames) to keep updating the frames in the label every 20 milliseconds.
  • When the Tkinter main loop ends, we release the webcam resource properly using cap.release() and destroy all OpenCV windows with cv2.destroyAllWindows().

Keep in mind that the after method of Tkinter is used to schedule the next frame update. The interval can be adjusted to be longer or shorter depending on the desired frame rate and the performance of the computer.


More Tags

cache-invalidation win32com date-comparison unauthorizedaccessexcepti if-statement html-email datetimeindex istio-gateway introspection boxplot

More Programming Guides

Other Guides

More Programming Examples