Open and Show Videos in Tkinter

Recently I came along the requirement to load a video into a Tkinter window. After some research in the web and experimenting I found the following, working solution (the snippet is just to demonstrate the approach; my used implementation is more complex):

import imageio
from tkinter import Tk, Label
from PIL import ImageTk, Image
from pathlib import Path

video_name = str(Path().absolute()) + '/../background.mp4'
video = imageio.get_reader(video_name)
delay = int(1000 / video.get_meta_data()['fps'])

def stream(label):

try:
image = video.get_next_data()
except:
video.close()
return
label.after(delay, lambda: stream(label))
frame_image = ImageTk.PhotoImage(Image.fromarray(image))
label.config(image=frame_image)
label.image = frame_image

if __name__ == '__main__':

root = Tk()
my_label = Label(root)
my_label.pack()
my_label.after(delay, lambda: stream(my_label))
root.mainloop()
Code language: Python (python)

Important to notice is here that Tkinter has his own update mechanism that processes events and updates the application window. Unlike other solutions that use threading (which leads to a flickering result), we use Tkinter’s own after method to register a callback.

Leave a Reply

Your email address will not be published. Required fields are marked *