You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CustomTkinter窗口中显示视频?自制Python播放器遇阻

在CustomTkinter中实现VLC视频播放功能

要在CustomTkinter窗口中显示VLC视频,核心是将VLC的视频输出绑定到CustomTkinter的组件句柄上。以下是修改后的完整实现代码,包含视频播放、文件选择、外观切换和窗口缩放功能:

前置准备

首先安装依赖库:

pip install python-vlc customtkinter

完整代码

import customtkinter
from customtkinter import filedialog
import vlc

# 初始化CustomTkinter
customtkinter.set_appearance_mode("dark")
customtkinter.set_default_color_theme("dark-blue")

# 替换原关键字变量名,避免语法错误
window_state = 1
media_player = None
video_frame = None

root = customtkinter.CTk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.geometry(f"{w}x{h}")
root.title("CustomVLC Player")

def init_vlc_player():
    """初始化VLC播放器并绑定到视频容器"""
    global media_player, video_frame
    # 创建纯黑背景的视频显示容器
    video_frame = customtkinter.CTkFrame(root, fg_color="black")
    video_frame.pack(fill="both", expand=True, padx=10, pady=10)
    
    # 初始化VLC实例与媒体播放器
    instance = vlc.Instance()
    media_player = instance.media_player_new()
    # 将播放器输出绑定到CustomTkinter组件的系统句柄
    media_player.set_hwnd(video_frame.winfo_id())

def select_file():
    """选择视频文件并开始播放"""
    global media_player
    file_path = filedialog.askopenfilename(
        filetypes=[("视频文件", "*.mp4 *.avi *.mkv *.mov *.flv")]
    )
    if not file_path:
        return
    # 加载选中的媒体文件并播放
    media = vlc.Media(file_path)
    media_player.set_media(media)
    media_player.play()

def change_mode():
    """切换明暗外观模式"""
    current_mode = customtkinter.get_appearance_mode()
    new_mode = "light" if current_mode == "dark" else "dark"
    customtkinter.set_appearance_mode(new_mode)

def change_size():
    """切换全屏/窗口显示模式"""
    global window_state
    if window_state % 2 == 1:
        root.attributes("-fullscreen", True)
    else:
        root.attributes("-fullscreen", False)
        root.geometry(f"{w}x{h}")
    window_state += 1

# 创建底部控制栏
control_frame = customtkinter.CTkFrame(root)
control_frame.pack(fill="x", padx=10, pady=(0,10))

# 添加操作按钮
btn_select = customtkinter.CTkButton(control_frame, text="选择视频", command=select_file)
btn_select.pack(side="left", padx=5, pady=5)

btn_mode = customtkinter.CTkButton(control_frame, text="切换外观", command=change_mode)
btn_mode.pack(side="left", padx=5, pady=5)

btn_size = customtkinter.CTkButton(control_frame, text="全屏/窗口", command=change_size)
btn_size.pack(side="left", padx=5, pady=5)

# 初始化播放器组件
init_vlc_player()

root.mainloop()

关键实现说明

  • 视频输出绑定:通过media_player.set_hwnd(video_frame.winfo_id())将VLC的视频渲染定向到CustomTkinter的CTkFrame组件,这是实现视频显示的核心步骤。
  • VLC核心逻辑:使用vlc.Instance()创建VLC运行实例,通过MediaPlayer对象完成媒体加载、播放控制。
  • 原代码修复:替换了原代码中使用Python关键字int作为变量名的错误,优化窗口缩放逻辑为直接切换系统全屏属性。
  • 界面结构优化:新增控制栏统一放置操作按钮,让界面布局更合理。

内容的提问来源于stack exchange,提问作者pierrepapierciseaux Lafontaine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 16:55:46