【问题标题】:Working with Tkinter, Progressbar, and Queue使用 Tkinter、Progressbar 和 Queue
【发布时间】:2013-05-20 08:41:00
【问题描述】:

我希望我的 Tkinter 进度条增量更新。我已经尝试按照here 中提到的示例进行操作。

最初,我尝试了不使用线程的代码。这导致“开始”按钮甚至出现之前的延迟。一旦我添加了线程部分,初始 UI 和 Progressbar 小部件就会正确显示。

但是,我仍然遇到进度条不会增加的问题。也许我的 Queue 部分代码正在破坏它?我做了一些实验,但最终得到的结果如下:

class MainUI:
    def __init__(self, master, queue):
        self.queue = queue
        self.master = master
        self.main_container = Frame(self.master)
        self.main_container.pack()
        self.counter = IntVar()
        self.btn_start = Button(self.main_container, command=self.btn_start_click)
        self.btn_start.configure(
            text="Start", background="Grey",
            padx=50
            )
        self.btn_start.pack(side=LEFT)

    def progress_bar(self):
        self.pbar_top = Toplevel(self.main_container)
        self.download_label = Label(
            self.pbar_top,
            text="Download Bar"
            )
        self.download_label.pack(side=TOP)

        self.download_bar = ttk.Progressbar(
            self.pbar_top, orient="horizontal",
            length=400, mode="determinate",
            variable=self.counter, maximum=5
            )
        self.download_bar.pack(side=TOP)

    def prog_bar_update(self, value):
        self.counter = value

    def btn_start_click(self):    
        self.progress_bar()

    def process_queue(self):
        while self.queue.qsize():
            try:
                value = self.queue.get(0)
                self.prog_bar_update(value)
            except Queue.Empty:
                pass

class Logic:
    def __init__(self, master):
        self.master = master
        self.queue = Queue.Queue()
        self.gui = MainUI(master, self.queue)
        t = threading.Thread(target=self.start_logic)
        t.start()
        self.periodic_call()

    def periodic_call(self):
        self.gui.process_queue()
        self.master.after(100, self.periodic_call)

    def start_logic(self):
        for i in range(4):
            time.sleep(2)
            increment = i
            self.queue.put(increment)

root = Tk()
root.title("Progress Bar Test")
main_ui = Logic(root)
root.mainloop()

上面的代码会显示进度条,但增量永远不会发生。我想我在这里遗漏了一些非常基本和明显的东西。有人可以请教我吗?

【问题讨论】:

    标签: python python-2.7 tkinter queue


    【解决方案1】:

    看看这行代码:

    self.counter = value
    

    在执行这行代码之前,self.counterIntVar 的一个实例。在此语句之后,self.counter 只是一个 int。将行更改为:

    self.counter.set(value)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-16
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-29
      相关资源
      最近更新 更多