""" Template for game with pause, restart and quit (here simple input in 'PRQ'
    using withdrawn tkinter window for cross platform getkey command

"""

from __future__ import print_function
import time

try:
    from Tkinter import *
except ImportError:
    from tkinter import *

class Keypress(Frame):
    def __init__(self, root):
        print('='*40)
        print('New game')
        self.paused = False
        self.count = 0
        self.command = ' '
        self.root = root
        self.root.bind_all('<Key>', self.key)
        self.root.withdraw()
        self.root.mainloop()

    def key(self, event):
        '''simplified key response, for full analysis of key see:
            http://www.daniweb.com/software-development/python/code/216830

        '''
        self.count += 1
        print(self.count, end= ': ')
        self.action(event.keysym)
        if self.command in 'qQ':
            self.root.destroy()
        elif self.command in'rR':
            self.__init__(self.root)
        
    def action(self, command):
        if command in 'rqRQ':
            self.command = command
        elif command in 'pP':
            self.paused = not self.paused
            print ('Pause on' if self.paused else 'Pause off')
        elif not self.paused:
            self.command = command
            print('Action with command %r' % command)
        else:
            print('Paused')

def play():
    reason = Keypress(Tk())
    print(reason.command,'(quited)')

if __name__ == '__main__':
    play()

Specialties:
IT/Science/Contracts/Religious translation/interpreting FIN-ENG-FIN
Python programming

2
Contributors
2
Replies
19
Views
6 Years
Discussion Span
Last Post by pyTony
0

I have tried this code and it does not seem to work. I think the problem is that if you withdraw the main window then it stops responding to events (without withdraw, if I make the root window focused, the program works fine). I have tested this on a Mac, with Python 2.7.2 and 3.2.2.

0

Thanks for announcing, as is the program works from IDLE, but indeed did not work from console.

<<original code-snippet corrected as requested>>

Edited by Nick Evan: Removed code + added comment

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.