【问题标题】:How to make the progressbar work, It freezes the window如何使进度条工作,它冻结窗口
【发布时间】:2020-02-19 05:52:43
【问题描述】:

我尝试制作进度条,但它没有工作,而是冻结了 tkinter 窗口,我也尝试关闭它,但它冻结了窗口

from tkinter import *
from tkinter.ttk import *
import time

root = Tk()


pbar = Progressbar(root, orient = HORIZONTAL,
                       length = 100, mode = 'determinate')


def bar():
    pbar['value'] = 20
    time.sleep(0.5)

    pbar['value'] = 40
    time.sleep(0.5)

    pbar['value'] = 60
    time.sleep(0.5)

    pbar['value'] = 80
    time.sleep(0.5)

    pbar['value'] = 100

pbar.pack()

Button(root, text = 'Start Bar', command = bar).pack()

root.mainloop()

如何让它发挥作用!

【问题讨论】:

  • 使用'root.update()'
  • 这是一个非常糟糕的主意@HardikJain;正确的做法是使用root.after 发起回调。

标签: python tkinter progress-bar


【解决方案1】:

虽然答案似乎有效,但它会在 0.5 秒 time.sleep 间隔内锁定您的 GUI。

更直接的方法是使用root.after:

...

def bar():
    pbar['value']+=20
    if pbar["value"]!=100:
        root.after(500, bar)

pbar.pack()

...

【讨论】:

  • 善用after - 您可能应该防止多次按下按钮,这样会在有时间完成之前多次启动栏。使用after_cancel。
【解决方案2】:

正确的方法是使用root.after,同时确保在进度条处于活动状态时放弃多次按下按钮:

这里我们使用带有默认值的关键字参数来识别调用是来自按钮还是来自回调。我们还将回调 id 存储在通过可变默认值关键字参数实现的闭包中;这使我们可以在工作完成后彻底取消进一步的回调。

import tkinter as tk
import tkinter.ttk as ttk


def bar(btn=True, status=[None]):
    """activates and updates the progress bar status
    while making sure that multiple button presses only 
    start it once.
    """

    if btn and status[0] is not None:
        return 'break'
    elif pbar['value'] < 100:
        pbar['value'], status[0] = pbar['value'] + 1, root.after(10, bar, False)
    else:
        root.after_cancel(status[0])
        pbar['value'], status[0] = 0, None


root = tk.Tk()
pbar = ttk.Progressbar(root, orient=tk.HORIZONTAL, length=100, mode='determinate') 
pbar.pack()
tk.Button(root, text='Start Bar', command=bar).pack()
root.mainloop()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    相关资源
    最近更新 更多