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

如何在customTkinter中通过YouTube URL播放视频?解决JS执行错误

解决方案:YouTube嵌入视频的JavaScript执行错误

针对你遇到的"An error occurred. Unable to execute JavaScript."问题,可按以下步骤解决:

1. 启用HtmlFrame的JavaScript支持

tkinterweb的HtmlFrame默认未启用JavaScript,而YouTube嵌入播放器依赖JS运行。初始化时需显式开启:

self.youtubeframe = HtmlFrame(self.visualisation_frame, js_enabled=True)

修改后的完整代码:

import customtkinter
from tkinterweb import HtmlFrame  

class App(customtkinter.CTk):
    def __init__(self):
        super().__init__()

        self.visualisation_frame = customtkinter.CTkFrame(self)
        self.visualisation_frame.pack(pady=20, padx=20)

        # 启用JavaScript支持
        self.youtubeframe = HtmlFrame(self.visualisation_frame, js_enabled=True)
        self.youtubeframe.grid(row=0, column=0, columnspan=2, padx=20, pady=(20, 5))

        video_embed_url = "https://www.youtube.com/embed/6Ejga4kJUts"
        self.youtubeframe.load_website(video_embed_url)


if __name__ == "__main__":
    app = App()
    app.mainloop()

2. 更新tkinterweb到最新版本

旧版本的tkinterweb可能存在JavaScript兼容问题,执行命令更新:

pip install --upgrade tkinterweb

3. 替代方案:使用cefpython3(更稳定的JS支持)

如果上述方法仍无法解决,可改用基于Chromium的cefpython3,它对现代JavaScript的支持更完善。示例代码如下:

import customtkinter
from cefpython3 import cefpython as cef
import sys

class App(customtkinter.CTk):
    def __init__(self):
        super().__init__()
        self.title("YouTube Player")
        self.geometry("800x600")

        # 初始化CEF
        cef.Initialize()

        self.visualisation_frame = customtkinter.CTkFrame(self)
        self.visualisation_frame.pack(pady=20, padx=20, fill="both", expand=True)

        # 创建CEF浏览器组件
        self.browser_frame = customtkinter.CTkFrame(self.visualisation_frame)
        self.browser_frame.pack(fill="both", expand=True, padx=10, pady=10)
        
        window_info = cef.WindowInfo()
        window_info.SetAsChild(self.browser_frame.winfo_id())
        self.browser = cef.CreateBrowserSync(window_info, url="https://www.youtube.com/embed/6Ejga4kJUts")

        # 绑定窗口关闭事件
        self.protocol("WM_DELETE_WINDOW", self.on_close)

    def on_close(self):
        self.browser.CloseBrowser()
        cef.Shutdown()
        self.destroy()

if __name__ == "__main__":
    app = App()
    app.mainloop()

使用前需安装依赖:

pip install cefpython3 customtkinter

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 14:40:04