在Tkinter的for循环中创建暂停

时间:2018-12-08 04:54:18

标签: python for-loop tkinter

在这种情况下,我要迭代self.players两次。对于每次迭代,我想在调用print方法之前暂停一秒钟。我怎样才能让他工作? 这是一个简化的示例:

import tkinter as tk

class Main(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.players = [1, 2, 3, 4, 5]
        self.play()

    def play(self):
        for x in range(2):
            for player in self.players:
                self.after(1000, self.print, player)

    def print(self, player):
        print(player)

if __name__ == '__main__':
    Main()

1 个答案:

答案 0 :(得分:0)

  1. 直接控制计数器

  2. self.after应该调用play方法,而不是print方法

    import tkinter as tk
    
    class Main(tk.Tk):
        def __init__(self):
             tk.Tk.__init__(self)
             self.counter=0
             self.players = [1, 2, 3, 4, 5]
             self.after(1000,self.play)
    
       def play(self):
             if self.counter<2:
                 for player in self.players:
                     (self.print(player))
                 self.counter+=1
                 self.after(1000,self.play)
    
       def print(self, player):
             print(player)
    
    if __name__ == '__main__':
       Main()