python调用ui界面播放视频代码
时间: 2023-08-25 17:06:26 浏览: 222
下面是一个使用Python调用UI界面播放视频的示例代码:
```python
import tkinter as tk
from tkinter import filedialog
import cv2
from PIL import Image, ImageTk
class VideoPlayer:
def __init__(self, root):
self.root = root
self.root.title("Video Player")
self.video_frame = tk.Frame(self.root)
self.video_frame.pack(side=tk.TOP)
self.btn_frame = tk.Frame(self.root)
self.btn_frame.pack(side=tk.BOTTOM)
self.video_path = None
self.video_cap = None
self.canvas = tk.Canvas(self.video_frame)
self.canvas.pack()
self.open_btn = tk.Button(self.btn_frame, text="Open Video", command=self.open_video)
self.open_btn.pack(side=tk.LEFT)
self.play_btn = tk.Button(self.btn_frame, text="Play", command=self.play_video)
self.play_btn.pack(side=tk.LEFT)
self.pause_btn = tk.Button(self.btn_frame, text="Pause", command=self.pause_video)
self.pause_btn.pack(side=tk.LEFT)
def open_video(self):
self.video_path = filedialog.askopenfilename(filetypes=[("Video Files", "*.mp4;*.avi")])
if self.video_path:
self.video_cap = cv2.VideoCapture(self.video_path)
self.play_video()
def play_video(self):
if self.video_cap and not self.video_cap.isOpened():
self.video_cap.open(self.video_path)
if self.video_cap and self.video_cap.isOpened():
ret, frame = self.video_cap.read()
if ret:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
image = Image.fromarray(frame)
image = image.resize((640, 480), Image.ANTIALIAS)
photo = ImageTk.PhotoImage(image=image)
self.canvas.create_image(0, 0, image=photo, anchor=tk.NW)
self.canvas.image = photo
self.root.after(30, self.play_video)
def pause_video(self):
if self.video_cap and self.video_cap.isOpened():
self.video_cap.release()
root = tk.Tk()
player = VideoPlayer(root)
root.mainloop()
```
这段代码使用了`tkinter`库创建了一个简单的UI界面,并使用`cv2`库读取和播放视频。通过点击"Open Video"按钮选择视频文件,然后点击"Play"按钮开始播放视频,点击"Pause"按钮暂停视频播放。
请确保安装了`tkinter`、`opencv-python`和`Pillow`库。你可以根据自己的需求进行修改和扩展。
阅读全文