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

Python开发YouTube视频下载器的错误与延迟问题排查

YouTube视频下载器问题修复方案

问题1:界面未显示“Download Completed”提示

  • 原因:下载操作阻塞了Tkinter主线程,界面无法及时更新;若移动文件环节出错,后续标题更新代码不会执行。
  • 修复:用threading将下载逻辑放到子线程,避免阻塞UI;添加异常捕获,确保操作状态能反馈到界面。

问题2:视频未保存到选定路径

  • 原因:select_path函数里没把用户选择的路径赋值给path_label的文本属性,导致user_path始终是初始提示文本,不是实际路径。
  • 修复:修改select_path函数,把选中的路径设置到path_label;同时直接用pytube的download方法指定输出路径,不用额外调用shutil.move。

问题3:控制台报错+下载耗时长

  • 原因:多余调用了moviepy的VideoFileClip加载视频,完全没必要,既浪费资源又增加耗时,还可能引发报错。
  • 修复:移除所有moviepy相关代码和导入。

修改后的完整代码

from tkinter import *
from tkinter import filedialog
from pytube import YouTube
import threading

screen = Tk()
screen.title("Youtube Downloader")
canvas = Canvas(screen, width=500, height=500)
canvas.pack()

def select_path():
    path = filedialog.askdirectory()
    if path:
        path_label.config(text=path)  # 将选中的路径赋值给标签文本

def download_video():
    def download_task():
        try:
            get_link = link_field.get()
            user_path = path_label.cget("text")
            # 检查是否选择了路径
            if user_path == "Select Local Path: ":
                screen.title("请先选择保存路径!")
                return
            
            screen.title('Downloading... Please wait...')
            # 直接指定下载路径,无需后续移动
            YouTube(get_link).streams.get_highest_resolution().download(output_path=user_path)
            screen.title('Download Completed!')
        except Exception as e:
            screen.title(f"下载出错:{str(e)}")
    
    # 开启子线程执行下载,避免阻塞UI
    threading.Thread(target=download_task, daemon=True).start()

logoimg = PhotoImage(file="images/download.png")
logoimg = logoimg.subsample(2, 2)
canvas.create_image(250, 80, image=logoimg)

link_field = Entry(screen, width=50)
link_label = Label(screen, text="Paste Download Link: ", font=("Sans Serif", 13))

canvas.create_window(250, 170, window=link_label)
canvas.create_window(250, 210, window=link_field)

path_label = Label(screen, text="Select Local Path: ", font=("Sans Serif", 13))
select_button = Button(screen, text="Select", command=select_path)

canvas.create_window(250, 270, window=path_label)
canvas.create_window(250, 320, window=select_button)

download_bttn = Button(screen, text="Download Video", font=("Sans Serif", 12), command=download_video)
canvas.create_window(250, 400, window=download_bttn)

screen.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 10:40:17