如何将进度条连接到函数?

2024-03-19

我正在尝试将进度条连接到我的项目的函数。

这是我到目前为止所拥有的,但我很确定它什么也没做:

def main():
    pgBar.start()
    function1()
    function2()
    function3()
    function4()
    pgBar.stop()

这是我制作进度条的代码(如果有帮助的话):

pgBar = ttk.Progressbar(window, orient = HORIZONTAL, length=300, mode = "determinate")
pgBar.place(x=45, y=130)

我一直在做一些研究并了解到 tkinter 窗口在运行函数或类似的东西时会冻结。有没有一种方法可以在主函数内部调用的每个函数末尾“解冻”窗口?


由于 tkinter 是单线程,你需要另一个线程来执行你的main功能无需冻结 GUI。一种常见的方法是工作线程将消息放入同步对象(如Queue http://docs.python.org/2/library/queue.html),GUI 部分使用此消息,更新进度条。

以下代码基于完整详细的example http://code.activestate.com/recipes/82965/在活动状态上:

import tkinter as tk
from tkinter import ttk
import threading
import queue
import time


class App(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        self.queue = queue.Queue()
        self.listbox = tk.Listbox(self, width=20, height=5)
        self.progressbar = ttk.Progressbar(self, orient='horizontal',
                                           length=300, mode='determinate')
        self.button = tk.Button(self, text="Start", command=self.spawnthread)
        self.listbox.pack(padx=10, pady=10)
        self.progressbar.pack(padx=10, pady=10)
        self.button.pack(padx=10, pady=10)

    def spawnthread(self):
        self.button.config(state="disabled")
        self.thread = ThreadedClient(self.queue)
        self.thread.start()
        self.periodiccall()

    def periodiccall(self):
        self.checkqueue()
        if self.thread.is_alive():
            self.after(100, self.periodiccall)
        else:
            self.button.config(state="active")

    def checkqueue(self):
        while self.queue.qsize():
            try:
                msg = self.queue.get(0)
                self.listbox.insert('end', msg)
                self.progressbar.step(25)
            except Queue.Empty:
                pass


class ThreadedClient(threading.Thread):

    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue

    def run(self):
        for x in range(1, 5):
            time.sleep(2)
            msg = "Function %s finished..." % x
            self.queue.put(msg)


if __name__ == "__main__":
    app = App()
    app.mainloop()

自从原始示例 http://code.activestate.com/recipes/82965/在我看来,ActiveState 有点混乱(ThreadedClientGuiPart,并且诸如控制从 GUI 生成线程的时刻之类的事情并不那么简单),我重构了它并添加了一个按钮来启动新线程。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将进度条连接到函数? 的相关文章

随机推荐