[英]Tkinter mainloop() not running - Python
I have designed somewhat of an AI to play 2048. I would like to display the game state after each move the AI makes. 我设计了一些AI来玩2048。我想在AI每次移动后显示游戏状态。 To do so, I have created a GUI using Tkinter.
为此,我使用Tkinter创建了一个GUI。 First time using Tkinter, and as the title suggests, it seems like my 'updateDisplay' method blocks the mainloop() from being called.
第一次使用Tkinter,正如标题所示,似乎我的“ updateDisplay”方法阻止了mainloop()的调用。 Any help would be appreciated.
任何帮助,将不胜感激。
The GUI will display if I remove the call to self.after(1000, self.updateDisplay(ai, game))
. 如果我删除对
self.after(1000, self.updateDisplay(ai, game))
的调用,则会显示GUI。 However, it will then obviously not update 但是,它显然不会更新
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)
When you do self.after(1000, self.updateDisplay(ai, game))
, you're calling self.updateDisplay
immediately rather than passing the function as an argument to after
. 当您执行
self.after(1000, self.updateDisplay(ai, game))
,您将立即调用self.updateDisplay
,而不是将函数作为参数传递给after
。 You need to get rid of the inner parentheses! 您需要摆脱内括号! According to the docs,
after
does take extra *args
, but it doesn't actually say what is done with them (maybe they're passed to the callback? I'm not sure). 根据文档,
after
确实需要额外的*args
,但实际上并没有说明对它们做了什么(也许它们已传递给回调函数?我不确定)。 Since ai
and game
are already attributes of self
, you don't actually need to pass them as arguments at all. 由于
ai
和game
已经是self
属性,因此您实际上根本不需要将它们作为参数传递。 Just use: 只需使用:
self.after(1000, self.updateDisplay)
And change the definition of updateDisplay
to: 并将
updateDisplay
的定义更改为:
def updateDisplay(self):
# use self.ai and self.game rather than ai and game in the implementation of the function
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.