下载文件时无法重命名文件

I cannot rename a file when it is being downloaded

下面是我下载 YouTube 视频然后将其转换为音频文件的代码。但是在重命名它时,出现错误。请解释我的问题,请给我一个解决方案。

import os
import tkinter as tk
from tkinter import ttk
from pytube import YouTube
from tkinter.filedialog import askdirectory
from tkinter.messagebox import askyesno, showinfo

当我使用它来重命名我的文件时,这个函数给我带来了问题。

def rename_file(file):
    def return_val():
        print(new_name.get())
        top.destroy()
        return(new_name.get())

    print(file)
    top = tk.Toplevel(root)
    top.title("Rename File")
    top.iconbitmap('icon.ico')
    top.geometry('400x130')

    tk.Label(top, text='Enter new name for the file: ', font='comicsansms 12').grid(row=0, column=0)
    new_name=tk.StringVar()
    new_name.set(file)

    name_entry = ttk.Entry(top, textvariable=new_name, font='comicsansns 12')
    name_entry.focus_force()
    name_entry.grid(row=0, column=1, pady=5)
    
    ttk.Button(top, text='Rename!', command=return_val, width=8).grid(row=3, column=1, pady=18, ipady=9)

这是从 YouTube 下载视频的主要功能。

def download_audio():
        try:
            global link_var
            global directory
    
            link = link_var.get() 
    
            yt = YouTube(link)
            title_lable = ttk.Label(root, text=f"Title: {yt.title}", font='lucida 12')
            title_lable.grid(row=3, column=0, pady=9, padx=4)
    
            confirmation = askyesno('Check Title', "Does the title match the video you wanna download?")
    
            if confirmation:
                video = yt.streams.filter(only_audio=True).first()
                video_file = video.download(output_path=directory)
                
                base, ext = os.path.splitext(video_file)
                audio_file = base + '.mp3'
    
                rename = askyesno('Rename File', 'Do you want to rename this file?')
                if rename:                 

在此功能结束之前,

                   obj = rename_file(audio_file.split('\')[-1])
                

它前进到下一行。

                   audio_file = os.path.join(directory, obj)
                   print(audio_file)
    
                os.rename(video_file, audio_file)
                showinfo("Downloaded", "Your Audio file is downloaded")
    
                link_var.set("")
                title_lable.config(text="")

错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "f:\Eriq\PYTHON\YT to Mp3 Converter\yttomp3.py", line 53, in download_audio
    audio_file = os.path.join(directory, obj)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\ntpath.py", line 115, in join
    genericpath._check_arg_types('join', path, *paths)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\genericpath.py", line 149, in _check_arg_types
    (funcname, s.__class__.__name__)) from None
TypeError: join() argument must be str or bytes, not 'NoneType'

您应该 rename_file() 像模态对话框一样工作:

def rename_file(file):
    def return_val():
        print(new_name.get())
        top.destroy()
        # return statement here is useless

    print(file)
    top = tk.Toplevel(root)
    top.title("Rename File")
    top.iconbitmap('icon.ico')
    top.geometry('400x130')

    tk.Label(top, text='Enter new name for the file: ', font='comicsansms 12').grid(row=0, column=0)
    new_name=tk.StringVar()
    new_name.set(file)

    name_entry = tk.Entry(top, textvariable=new_name, font='comicsansns 12')
    name_entry.focus_force()
    name_entry.grid(row=0, column=1, pady=5)

    tk.Button(top, text='Rename!', command=return_val, width=8).grid(row=3, column=1, pady=18, ipady=9)

    root.wait_window(top) # wait for the window to close
    return new_name.get() # return the name entered

还建议在以下行中使用 os.path.basename() 而不是 split()

obj = rename_file(audio_file.split('\')[-1])

所以把上面这行改成:

obj = rename_file(os.path.basename(audio_file))