在ac和download_button 之间添加一个用于显示下载进度条的方法,我要在主面板上能看到
时间: 2024-04-17 13:27:26 浏览: 131
你可以通过在root上添加一个进度条来显示下载的进度。以下是修改后的代码:
```python
import re
import tkinter
import requests
import threading
import tqdm as tt
from pydub import AudioSegment
from tkinter import ttk
root = tkinter.Tk()
root.title('在线视频解析')
root.geometry('500x590+550+350')
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0'}
ac = tkinter.Listbox(root, width=50, height=20, font=('黑体', 12))
ac.grid(row=2, columnspan=10, sticky="n" + "s" + "w" + "e")
def sousuo():
i = b1.get()
ac.delete(0, 'end')
def extract_music_info(content):
p = '<em>|</em>'
content = re.sub(p, '', content, flags=re.S)
pattern = re.compile('subject.*?href="(.*?)">(.*?)</a>', flags=re.S)
return pattern.findall(content)
def search_music():
url = 'https://www.hifini.com/search-' + i + '-1.htm'
response = requests.get(url=url, headers=headers)
return response.text
def update_listbox(music_list):
for music in music_list:
pppp = music[1] + ":" + music[0]
ac.insert('end', pppp)
content = search_music()
music_list = extract_music_info(content)
update_listbox(music_list)
def xiazzi():
def download_music():
ppp = ac.get(ac.curselection())
pp = re.search('thread.*?htm', ppp)
v = pp.group()
url1 = 'https://www.hifini.com/' + v
response = requests.get(url=url1, headers=headers)
ppp = response.text
l2 = re.search('<script>.*?title:..(.*?).,.*?author:.(.*?).,.*?url:..(.*?).,', ppp, flags=re.S)
p = 'https://www.hifini.com/' + l2.group(3)
response = requests.get(url=p, headers=headers, stream=True) # 设置 stream=True 以启用流式下载
total_size = int(response.headers.get('Content-Length'))
music_name = '{}-{}.m4a'.format(l2.group(2), l2.group(1))
progress_bar = ttk.Progressbar(root, length=300, mode='determinate') # 创建进度条
progress_bar.grid(row=4, column=0, columnspan=5, padx=10, pady=10)
with open(music_name, 'wb') as f:
for data in response.iter_content(chunk_size=1024):
f.write(data)
downloaded_size = f.tell()
progress = int((downloaded_size / total_size) * 100)
progress_bar['value'] = progress # 更新进度条
root.update_idletasks() # 更新UI界面
if music_name.endswith('.m4a'):
mp3_name = music_name[:-4] + '.mp3'
audio = AudioSegment.from_file(music_name, format='m4a')
audio.export(mp3_name, format='mp3')
print(mp3_name)
else:
print(music_name)
progress_bar.destroy() # 销毁进度条
threading.Thread(target=download_music).start()
a1 = tkinter.Label(root, text='音乐下载器', anchor="center", font=('黑体', 24))
a1.grid(row=0, columnspan=10, sticky="n" + "s" + "w" + "e")
b1 = tkinter.Entry(root, width=35, font=('黑体', 16), )
b1.grid(row=1, column=3, padx=15)
search_button = tkinter.Button(root, text='搜索', command=sousuo)
search_button.grid(row=1, column=4)
download_button = tkinter.Button(root, text='下载', command=xiazzi)
download_button.grid(row=3, column=4)
root.mainloop()
```
这样,当点击下载按钮后,会在主面板上添加一个进度条,显示下载的进度。下载完成后,进度条会被销毁。
阅读全文