2017-02-03 66 views
0

我正在使用Tkinter在Python 2.7中編寫一個簡單的GUI程序。 應提示用戶「按任意按鈕繼續」。如何在繼續之前讓Tkinter等待按鍵?

目前,(簡體),代碼如下所示:

# -*- 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

有很多方法可以做得更好,但這裏有一個開始。 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() 
相關問題