Python中的进度条和组合

时间:2012-12-13 08:05:21

标签: python combinations tk itertools ttk

我正在使用itertools.combinations模块来查找大量组合。当我的程序找到它的所有组合(很多组合)时,它会检查每个组合的总和是否为某个数字,然后将该组合存储在列表中。

from itertools import *
from math import *
import Tkinter as tk
import ttk


x = int(raw_input('Enter number of combinations: '))
z = int(raw_input('Enter sum number: '))


def combinator():
    comb = combinations(range(100), x)
    for i in comb:
        yield i

my_combinations = []
combination_s = combinator()
for i in combination_s:
    print i
    c = list(i)
    if fsum(c)==z:
        my_combinations.append(c)

print my_combinations

root = tk.Tk()
root.title('ttk.Progressbar')
pbar = ttk.Progressbar(root, length=300, mode='determinate', maximum = 100)
pbar.pack(padx=5, pady=5)
root.mainloop()

我想让ttk.progressbar显示每次程序评估组合总和时的进度。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

这是一个增加每个组合的进度条的示例。它只是等待很短的时间,但您可以轻松更改它以在ProgBarApp.start而不是time.sleep中的for循环中进行一些计算

from Tkinter import *
from itertools import combinations
import ttk
import time

class ProgBarApp:
    def __init__(self):
        self.vals = range(1, 20)
        self.combs = list(combinations(self.vals,3))
        self.n = len(self.combs)
        self.progressbar = ttk.Progressbar(root, maximum = self.n+1)
        self.progressbar.pack()

    def start(self):
        for c in self.combs:
            self.progressbar.step()
            time.sleep(0.01)    
            root.update()
        root.destroy()

root = Tk()
p = ProgBarApp()
root.after(0, p.start())
root.mainloop()