【问题标题】:Update text in real time by calling two functions Pygame通过调用两个函数 Pygame 实时更新文本
【发布时间】:2019-09-22 05:44:59
【问题描述】:

我有一个程序,它接受用户的输入并使用Population() 函数显示输入的多种变体。 store_fit 函数将这些不同的变体添加到列表中,然后将它们删除,以便列表一次仅填充一个变体。

我希望能够从列表中获取变体并使用它来更新我的文本。但是,我的程序仅在 Population 函数完成后更新文本。如何运行Population 函数并同时更新我的​​文本?

代码:

fit = []
...

def store_fit(fittest): # fittest is each variation from Population
    clear.fit()
    fit.append(fittest)
...

pg.init()
...
done = False

while not done:
...
    if event.key == pg.K_RETURN:
        print(text)
        target = text
        Population(1000) #1000 variations
        store_fit(value)
        # I want this to run at the same time as Population
        fittest = fit[0]
...
top_sentence = font.render(("test: " + fittest), 1, pg.Color('lightskyblue3'))
screen.blit(top_sentence, (400, 400))

【问题讨论】:

    标签: python pygame


    【解决方案1】:

    我建议将Population 设为生成器函数。见The Python yield keyword explained

    def Populate(text, c):
        for i in range(c):
    
            # compute variation
            # [...]
    
            yield variation
    

    创建一个迭代器并使用next() 检索循环中的下一个变体,这样您就可以打印每个变体:

    populate_iter = Populate(text, 1000)
    
    final_variation = None
    while not done:
    
        next_variation = next(populate_iter, None)
        if next_variation :
            final_variation = next_variation 
    
            # print current variation
            # [...]
    
        else:
            done = True
    
    

    根据评论编辑:

    为了让我的问题简单,我没有提到 Population 是一个类 [...]

    当然Populate can be a class 也是。在这种情况下,您必须实现 object.__iter__(self) 方法。例如:

    class Populate:
        def __init__(self, text, c):
            self.text = text
            self.c    = c
    
        def __iter__(self):
            for i in range(self.c):
    
                # compute variation
                # [...]
    
                yield variation
    

    通过iter() 创建一个迭代器。例如:

    populate_iter = iter(Populate(text, 1000))
    
    final_variation = None
    while not done:
    
        next_variation = next(populate_iter, None)
        if next_variation :
            final_variation = next_variation 
    
            # print current variation
            # [...]
    
        else:
            done = True
    

    【讨论】:

    • 这是正确的方式去恕我直言。我在这个答案中使用了类似的方法:stackoverflow.com/a/53589557/142637
    • 为了让我的问题简单,我没有提到Population 是一个类,它的__init__ 函数是调用其他函数的函数。当我尝试在__init__ 内部屈服时,我被告知它不应该返回生成器。有没有办法解决这个问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    相关资源
    最近更新 更多