简体   繁体   中英

Python Tkinter after() does not work as expected

I am implementing the Reversi/Othello board game at Python using Tkinter for the GUI. The issue is that when a player makes a move I want each piece to be drawn with a time interval. So if 3 discs are to be drawn, I want the first disc to be drawn, then the second one after x ms , and so forth.

def draw_game(self,delay=True):

    # indexes of pieces on the board
    idxs = np.where(self._gameImage >0);


    for (row,column) in zip(idxs[0],idxs[1]):
    # Convert row,column to canvas coordinates
        x1,y1,x2,y2 = self.convert_idx(col=column-1,row=row-1)
        if delay:
        #draw pieces with 500ms delay in between
            self.after(500,self.draw_piece,row,column)
        else:
            self.draw_piece(row,column)

# function that draws a single piece(disc) on the board

def draw_piece(self,row,column):
    x1,y1,x2,y2 = self.convert_idx(col=column-1,row=row-1)
    self.canvas.create_oval(x1,y1,x2,y2,fill=self.number_to_color(self._gameImage[row,column]))  

So one would expect that each piece will be drawn with 500ms time interval between the current and the next piece. Instead, when I run the code, there is an initial time interval of 500ms and then all the pieces are drawn at once. I tried to run with -u but the behavior was the same. Any help? This should be fairly simple

I think your the placement of your:

  self.after(500,self.draw_piece,row,column) 

Needs to be moved to the end of your draw_piece() function. Here's another question that demonstrates the placement. Tkinter understanding after() It should call back to the function that its being used in.

    # function that draws a single piece(disc) on the board

def draw_piece(self,row,column):
    x1,y1,x2,y2 = self.convert_idx(col=column-1,row=row-1)
    self.canvas.create_oval(x1,y1,x2,y2,fill=self.number_to_color(self._gameImage[row,column]))
    self.after(500,self.draw_piece,row,column)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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