Tkinter mainloop()没有运行 - Python

时间:2016-05-24 03:33:01

标签: python tkinter

我已经设计了一些AI来玩2048.我想在AI每次移动后显示游戏状态。为此,我使用Tkinter创建了一个GUI。 第一次使用Tkinter,正如标题所示,似乎我的'updateDisplay'方法阻止了mainloop()被调用。任何帮助将不胜感激 如果我删除了对self.after(1000, self.updateDisplay(ai, game))的呼叫,将显示GUI。但是,它显然不会更新

class GameGrid(Frame):
    def __init__(self,ai, game):
        Frame.__init__(self)
        self.game = game
        self.ai = ai
        self.grid()
        self.master.title('2048')

        #self.gamelogic = gamelogic

        self.grid_cells = []
        self.init_grid()
        self.update_grid_cells()
        self.after(1000, self.updateDisplay(ai, game))
        self.mainloop()


    def updateDisplay(self, ai, game):
        game.move(ai.nextMove(4))
        print "hello"
        for i in range(GRID_LEN):
            for j in range(GRID_LEN):
                new_number = int(game.state[i][j])
                if new_number == 0:
                    self.grid_cells[i][j].configure(text="", bg=BACKGROUND_COLOR_CELL_EMPTY)
                else:
                    self.grid_cells[i][j].configure(text=str(new_number), bg=BACKGROUND_COLOR_DICT[new_number], fg=CELL_COLOR_DICT[new_number])
        if game.over:
            if game.won:
                print 'You Won!'
            else:
                print 'Game Over :( Score:', game.score
            return 0
        else: 
            print "test"
            self.after(10000, self.updateDisplay(ai, game))               



if __name__ == "__main__":
    game = Game()
    ai = AlphaBetaRecursive(game)
    gui = GameGrid(ai, game)

1 个答案:

答案 0 :(得分:2)

执行self.after(1000, self.updateDisplay(ai, game))时,您立即调用self.updateDisplay,而不是将该函数作为参数传递给after。你需要摆脱内在的括号!根据文档,after确实需要额外*args,但它实际上并没有说明对它们做了什么(也许它们已经传递给了回调?我' m不确定)。由于aigame已经是self的属性,因此您根本不需要将它们作为参数传递。只需使用:

self.after(1000, self.updateDisplay)

并将updateDisplay的定义更改为:

def updateDisplay(self):
    # use self.ai and self.game rather than ai and game in the implementation of the function
    ...