插座时冷冻gui

时间:2017-07-23 11:27:29

标签: python sockets user-interface

我正在构建一个允许用户访问的小gui应用程序 从服务器下载文件。它主要用于socket和tkinter。 但是当我下载文件(例如电影)时,需要花费一些时间,例如5分钟。并且在那个时候我想要一个进度条,它将进行循环,直到文件完全下载。但是当客户端使用sock.recv逐行获取文件数据时, 所有gui程序都冻结了! 因此,进度条无法移动, 我不能按任何按钮。 所以我的问题是 - 我该如何解决?意味着gui应用程序在从服务器获取数据时不会堆叠,然后我可以使进度条工作。 非常感谢你们。

2 个答案:

答案 0 :(得分:0)

在这里,我尝试描述(主要是伪代码)如何使用进度条实现非阻塞下载功能。

希望它有所帮助。

def update_progress(percentage):
    # update your progress bar in GUI

def download(callback):
    # implement your download function
    # check the full size of the file to be downloaded.
    # try to download a reasonable amount at once
    # call callback with percentage that you have downloaded to update GUI

    total = 1000000 # get total size of the file to be downloaded.
    current = 0
    block_size = 1000 # i.e., 1 KB

    while True:
        # do required operations to download data of block_size amount
        # example: sock.recv(block_size)
        current += block_size

        # calculate downloaded percentage
        percentage = (block_size * 100) / total # you may add precision if you prefer

        # call the callback function to update GUI based on the downloaded percentage
        callback(percentage)

        # check if download completed
        if current >= total:
            break

def start_download(): # bind this function to your button's click on GUI.
    # import threading

    # create a thread to execute download
    # see how 'update_progress' is passed as an argument
    thread = threading.Thread(target=download, args=[update_progress])
    thread.start()

    # execution will not be blocked here as the thread runs in the background.
    # so, any code here will run without waiting for download to be completed.

答案 1 :(得分:0)

谢谢你们的帮助,尤其是你们ohannes,我在后台使用过 线程类,这是代码:(您需要将' root'更改为您的tkinter窗口的名称)

jaxb