如何读取save.txt文件并将其设置为label

2024-05-21 05:25:51 发布

您现在位置:Python中文网/ 问答频道 /正文

(我正在用tkinter和pytube制作gui应用程序,它将把你的youtube视频下载到你的定位目录。) 你好,我在路上用Python做自己的应用程序,但这并不容易。我想不出解决办法。我希望我的应用程序进行保存。每次我选择一个目录时,它都会写入save.txt文件,但当我启动应用程序时,我不知道如何将该文件加载到显示当前目录的标签上。我还想更改ytbvideo.download(path)。我想读取save.txt文件,而不是路径。在我的saves.txt文件中只有一个目录。例如,save.txt中现在是C:/Python/VideoDownloader,因此如果应用程序读取save.txt,我想这应该不会是问题。这是我的代码,它运行良好,所以唯一的问题是,我不知道要添加什么这是我的代码:

import os
from tkinter import Text, Label, Tk, Entry, StringVar, Button
from tkinter import filedialog
import tkinter as tk



root= Tk()
root.geometry('600x400')
root.title('Youtube Video Downloader')
root.configure(bg='gray')



Label_1=Label(root,text="Youtube video downloader", font=("bold",20), bg='gray')
Label_1.place(x=150,y=10)

Label_2=Label(root, text="Paste the link here", font=(10), bg='gray')
Label_2.place(x=240, y=75)



mylink=StringVar()

pastelink=Entry(root, width=60, textvariable=mylink)
pastelink.place(x=140, y=100)



def chooseDir():

   
    global path
    path = filedialog.askdirectory(title="Choose a download directory")
    tk.Label(root, text=path, bg='gray').place(x=240,y=300)
    saves()

def downloadVideo():
    videoLink=str(mylink.get())
    ytbvideo=YouTube(videoLink).streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first()
    ytbvideo.download(path)




def saves():
    saves = open('data.txt', 'w')
    saves.write(path)   



    
def quitApp():
    root.destroy()
    



   

Button(root,text="Download video", width=20, bg='black',fg="white", command=downloadVideo).place(x=240, y=130)
Button(root,text="Choose location", width=20, bg='black',fg="white", command=chooseDir).place(x=240, y=160)
Label_3=Label(root, text="Curent location: ", font=("bold"), bg='gray')
Label_3.place(x=250, y=245)

Label_3=Label(root, text="by yakubiq", font=("bold"), bg='gray')
Label_3.place(x=0, y=375)

Button(root,text="Quit", width=20, bg='black', fg='white', command=quitApp).place(x=445, y=370)






root.mainloop()

Tags: 文件pathtextimporttxt应用程序tkintersave
2条回答

您必须在读取模式下打开save.txt,如下所示:

 savesReader = open("data.txt", 'r')

然后可以使用savesReader.read()从“data.txt”文件中读取

只要这样做:

var=open('[file directory]', 'r')
myvar= var.readlines()
tklabel=Label(root, text=f"{myvar}", font=(10), bg='gray')
var.close()

相关问题 更多 >