简体   繁体   English

python中的进度条

[英]progress bar in python

I have created token in tkinter window which changes the value each 10 seconds. 我在tkinter窗口中创建了令牌,该令牌每10秒更改一次值。 I want to improve it and add progress bar. 我想改善它并添加进度条。 I know about ready libraries, but I want to use my personal code. 我了解现成的库,但是我想使用我的个人代码。 My question is how to slow down the loop so the current value will be conveyed to string variable and after one second another value according to loop progress etc. My code just needs this "stopper". 我的问题是如何减慢循环速度,以便根据循环进度等将当前值传送到字符串变量,并在一秒钟后将另一个值传送给我。我的代码仅需要此“停止器”。 I could use 10 different functions and just triger after() but it doesn't look good and also my program crashes after a while. 我可以使用10个不同的函数,而只能触发after(),但它看起来并不好,并且一段时间后我的程序也会崩溃。

def count(self):
        k =[" l", " l", " l"," l"," l"," l"," l"," l"," l"," l"]
        for x in range(9,0,-1):
                self.test_var.set(k[x]*x)

Edit: Here is a generalized method, which should give the idea of how to solve this problem. 编辑:这是一种通用方法,应该给出如何解决此问题的想法。 It contains all necessary parts, but it must be implemented into right places of your code. 它包含所有必要的部分,但是必须在代码的正确位置实现。

To make sure your tkinter window wouldn't freeze during the update phase, you have to do the progress bar updating in another thread. 为了确保tkinter窗口在更新阶段不会冻结,您必须在另一个线程中进行进度条更新。

To call the method repeatedly after a certain time you can use time.sleep() method and a recursive method to call itself again and again. 要在一定时间后重复调用该方法,可以使用time.sleep()方法和递归方法一次又一次地调用自身。

import threading
import time


def change_progressbar(bar):
    # If there is more progress bar points to display, then do it
    if bar > 0:
        print(bar * ' l')  # Change your var here instead of printing
        time.sleep(10) # Wait 10 seconds
        change_progressbar(bar - 1) # Call itself again with one less point in a progress bar

# Let's call a method in new thread, with argument bar=10, which
# defines how many progress bar points there will be at start.
progressbar_thread = threading.Thread(target=change_progressbar, args=[10])
progressbar_thread.start()

# Output:  
# l l l l l l l l l l
# l l l l l l l l l
# l l l l l l l l
# l l l l l l l
# l l l l l l
# l l l l l
# l l l l
# l l l
# l l
# l

The "stopper" you are looking for is time.sleep() 您正在寻找的“停止器”是time.sleep()

The sleep function needs one argument, which is the amount of seconds to wait. sleep函数需要一个参数,即等待的秒数。 This can also be a float like 0.5 也可以是0.5的浮点数

You use it like this: 您可以这样使用它:

import time

while True:
    time.sleep(1)
    print("One second has passed")

This code will print something every second. 此代码将每秒打印一些内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM