首页 > 解决方案 > 使用 PySimpleGUI,如何让它下载带有进度条的文件?

问题描述

我想知道如何制作一个 PySimpleGUI 进度条,该进度条会根据下载文件进行相应更新。

(由于我在 macOS 上,我将不得不更改文件目录,但如果您目前在 Windows 或 Linux 上,只需以该目录格式编写它,因为我知道 macOS 的目录结构。)

我知道我可以做些什么来下载文件(使用 JSON API 和 url-lib 的请求来检索文件)

所以如果有人能帮我做这个,谢谢!

标签: pythonpython-3.xpysimplegui

解决方案


给你的例子,

在此处输入图像描述

import threading
from time import sleep
from random import randint
import PySimpleGUI as sg

def download_file(window):
    for count in range(0, 101, 2):     # Download file block by block
        sleep(0.1) 
        window.write_event_value('Next', count)

sg.theme("DarkBlue")

progress_bar = [
    [sg.ProgressBar(100, size=(40, 20), pad=(0, 0), key='Progress Bar'),
     sg.Text("  0%", size=(4, 1), key='Percent'),],
]

layout = [
    [sg.Button('Download')],
    [sg.pin(sg.Column(progress_bar, key='Progress', visible=False))],
]
window       = sg.Window('Title', layout, size=(600, 80), finalize=True,
    use_default_focus=False)
download     = window['Download']
progress_bar = window['Progress Bar']
percent      = window['Percent']
progress     = window['Progress']
while True:
    event, values = window.read()
    if event == sg.WINDOW_CLOSED:
        break
    elif event == 'Download':
        count = 0
        download.update(disabled=True)
        progress_bar.update(current_count=0, max=100)
        progress.update(visible=True)
        thread = threading.Thread(target=download_file, args=(window, ), daemon=True)
        thread.start()
    elif event == 'Next':
        count = values[event]
        progress_bar.update(current_count=count)
        percent.update(value=f'{count:>3d}%')
        window.refresh()
        if count == 100:
            sleep(1)
            download.update(disabled=False)
            progress.update(visible=False)

window.close()

推荐阅读