在继续之前,如何让Tkinter等待按键?

时间:2017-02-03 16:29:06

标签: python user-interface events tkinter

我正在使用Tkinter在Python 2.7中编写一个简单的GUI程序。 应提示用户“按任意按钮继续”。

目前,(简化)代码如下所示:

# -*- coding: utf-8 -*-
from Tkinter import *

class App():
    def __init__(self,root):
        Label(text="Press any key to continue!").grid(row=0,column=0)
        self.game()

    def game(self):       
        # some method to check if the user has pressed any key goes here
        Label(text="The Game is starting now!").grid(row=0,column=0)

    def key(self,event):
        print event.char
        return repr(event.char)


root = Tk() 
game_app = App(root)
root.bind('<Key>',game_app.key)
root.mainloop()

你知道一种有效的方法吗?

1 个答案:

答案 0 :(得分:1)

有很多方法可以做得更好,但这是一个开始。 self.state应该是一个枚举,因此明确定义了可能的状态。

https://gist.github.com/altendky/55ddb133cb3c9624546fdf8182564f07

# -*- coding: utf-8 -*-
from Tkinter import *

class App():
    def __init__(self,root):
        Label(text="Press any key to continue!").grid(row=0,column=0)
        self.state = 'startup'

    def loop(self):       
        # some method to check if the user has pressed any key goes here
        if self.state == 'startup':
            Label(text="The Game is starting now!").grid(row=0,column=0)
        elif self.state == 'running':
            Label(text="The Game is running now!").grid(row=0,column=0)

        root.after(20, self.loop)

    def key(self,event):
        if self.state == 'startup':
            self.state = 'running'


root = Tk() 
game_app = App(root)
root.bind('<Key>',game_app.key)
root.after(20, game_app.loop)
root.mainloop()