Tkinter YouTube下载按钮无法识别链接,报RegexMatchError如何解决?
解决Tkinter YouTube下载器的RegexMatchError问题
我是编程新手,首次使用Tkinter开发YouTube下载器。点击Download按钮后代码无法下载视频,触发RegexMatchError,推测问题出在yt = YouTube(f"{url}")这行,恳请协助解决。
原代码
import tkinter as tk from tkinter import ttk from tkinter.messagebox import showinfo from pytube import YouTube root = tk.Tk() root.geometry("400x200") root.resizable(False, False) root.title("Youtube Downloader") tk.Label(root, text="Hello :)\nWelcome to Youtube Downloader.\n").pack() url = tk.StringVar() # Link frame link = ttk.Frame(root) link.pack(padx=10, pady=10, fill='x', expand=True) # Link link_label = ttk.Label(link, text="Enter the Youtube link:\n") link_label.pack(fill='x', expand=True) link_entry = ttk.Entry(link, textvariable=url) link_entry.pack(fill='x', expand=True) link_entry.focus() # download button def download_clicked(): print("Welcome to Youtube Downloader.") showinfo( title='Information', message='Download has began!' ) yt = YouTube(f"{url}") stream = yt.streams.get_by_itag(22) size = round(stream.filesize / 10 ** 6, 2) print(f"Downloading {yt.title}, \n Length: {yt.length} seconds, \n Size: {size} MBs") download_button = ttk.Button( root, text='Download', compound=tk.LEFT, command=download_clicked ) download_button.pack(ipadx=5, ipady=5, expand=True) # Exit button exit_button = ttk.Button( root, text='Exit', command=lambda: root.quit() ) exit_button.pack( ipadx=5, ipady=5, expand=True, side="left" ) try: from ctypes import windll windll.shcore.SetProcessDpiAwareness(1) finally: root.mainloop()
报错信息
Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__ return self.func(*args) File "c:\Users\hp\Desktop\git\YoutubeDownloader\tkinter yt dowloader.py", line 36, in download_clicked yt = YouTube(f"{url}") File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\pytube\__main__.py", line 71, in __init__ self.video_id = extract.video_id(url) File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\pytube\extract.py", line 133, in video_id return regex_search(r"(?:v=|\/)([0-9A-Za-z_-]{11}).*", url, group=1) File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\pytube\helpers.py", line 129, in regex_search raise RegexMatchError(caller="regex_search", pattern=pattern) pytube.exceptions.RegexMatchError: regex_search: could not find match for (?:v=|\/)([0-9A-Za-z_-]{11}).*
问题原因与修复方案
核心问题:
url是Tkinter的StringVar对象,直接用f"{url}"转换字符串时,得到的是对象描述文本(类似PY_VAR0),而非用户输入的YouTube链接,导致pytube无法解析视频ID,触发RegexMatchError。修复步骤:
- 将
yt = YouTube(f"{url}")修改为yt = YouTube(url.get()),调用get()方法获取StringVar中存储的实际链接文本。 - 原代码仅获取了视频流信息,未执行下载操作,需添加
stream.download()启动下载。 - 可选:添加输入校验,防止空链接或无效链接,避免不必要的报错。
- 将
修改后的完整代码
import tkinter as tk from tkinter import ttk from tkinter.messagebox import showinfo, showerror from pytube import YouTube root = tk.Tk() root.geometry("400x200") root.resizable(False, False) root.title("Youtube Downloader") tk.Label(root, text="Hello :)\nWelcome to Youtube Downloader.\n").pack() url = tk.StringVar() # Link frame link = ttk.Frame(root) link.pack(padx=10, pady=10, fill='x', expand=True) # Link link_label = ttk.Label(link, text="Enter the Youtube link:\n") link_label.pack(fill='x', expand=True) link_entry = ttk.Entry(link, textvariable=url) link_entry.pack(fill='x', expand=True) link_entry.focus() # download button def download_clicked(): print("Welcome to Youtube Downloader.") video_url = url.get().strip() if not video_url: showerror(title="Error", message="请输入YouTube链接") return try: showinfo(title='Information', message='下载已开始!') yt = YouTube(video_url) stream = yt.streams.get_by_itag(22) # 720p MP4格式 if not stream: showerror(title="Error", message="无法找到指定格式的视频流") return size = round(stream.filesize / 10 ** 6, 2) print(f"正在下载 {yt.title}, \n 时长: {yt.length} 秒, \n 大小: {size} MB") # 执行下载,默认保存到当前目录 stream.download() showinfo(title="Success", message="下载完成!") except Exception as e: showerror(title="Error", message=f"下载失败: {str(e)}") print(f"错误信息: {str(e)}") download_button = ttk.Button( root, text='Download', compound=tk.LEFT, command=download_clicked ) download_button.pack(ipadx=5, ipady=5, expand=True) # Exit button exit_button = ttk.Button( root, text='Exit', command=lambda: root.quit() ) exit_button.pack( ipadx=5, ipady=5, expand=True, side="left" ) try: from ctypes import windll windll.shcore.SetProcessDpiAwareness(1) finally: root.mainloop()
内容的提问来源于stack exchange,提问作者Gray Black
相关产品推荐
相关产品推荐

