自我。“” after()不能正常工作?

时间:2013-06-04 21:41:35

标签: python class canvas tkinter

我试图让一个计时器每隔一秒执行一段代码,比如在python中使用tkinter。但是,不是每秒执行代码,而是在画布上移动标签,它似乎缓冲并等待循环结束,然后才显示移动的标签。下面是我认为发现问题的编码。我个人认为第二个函数中的for循环会产生问题,但我不知道如何解决这个问题。

def roll(self):
    number=randint(2,12)
    print number
    if self.a==0:
        self.place_player_1(self.start_turn_pos_1,number+self.start_turn_pos_1)
        self.start_turn_pos_1+=number
    elif self.a==1:
        self.place_player_2(self.start_turn_pos_2,number+self.start_turn_pos_2)
        self.start_turn_pos_2+=number
    return number

def place_player_1(self,start_turn_pos_1,number):
    #Define the board
    for i in range(self.start_turn_pos_1,number+1,1):
        self.c.after(1000,self.move_1(i))

def move_1(self,i):
    e1=streets_x[i]
    g1=streets_y[i]
    self.label_player1.place(x=e1,y=g1)

2 个答案:

答案 0 :(得分:2)

self.move_1(i)立即调用该方法。推迟通话:

self.c.after(1000, self.move_1, i) #note: no parentheses

要每秒重复一次通话,请在.after方法结束时添加self.move_1来电:

def place_player_1(self,start_turn_pos_1,number):
    self.c.after(1000, self.move_1, start_turn_pos_1, number) # call in a sec

def move_1(self,i, limit):
    e1=streets_x[i]
    g1=streets_y[i]
    self.label_player1.place(x=e1,y=g1)
    if i < limit: # schedule the next call
       self.c.after(1000, self.move_1, i + 1, limit)

请参阅setTimeout(), setInterval() analogs in Python using tkinter, or gtk, or twisted

答案 1 :(得分:0)

所有函数调用同时发生:

self.c.after(1000,self.move_1(i))

因为在1000毫秒之后调用。

使每个步骤的延迟更大。例如:

def place_player_1(self,start_turn_pos_1,number):
    #Define the board
    delay = 1000
    for index, i in enumerate(range(self.start_turn_pos_1, number + 1), 1):
        self.c.after(delay * index, self.move_1, i)

现在,您可以安排不同时间的函数调用。