Tkinter for console getkey, Pause/Restart/Quit

TrustyTony 2 Tallied Votes 2K Views Share

This is similar to earlier posts in DaniWeb by vegaseat, but it demonstrates getkey with withdrawn tkinter, restart inside object by re-calling it's __init__ method.

""" 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

    from Tkinter import *
except ImportError:
    from tkinter import *

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

    def key(self, event):
        '''simplified key response, for full analysis of key see:

        self.count += 1
        print(self.count, end= ': ')
        if self.command in 'qQ':
        elif self.command in'rR':
    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)

def play():
    reason = Keypress(Tk())

if __name__ == '__main__':
Szepi 0 Newbie Poster

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.

TrustyTony 888 pyMod Team Colleague Featured Poster

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

<<original code-snippet corrected as requested>>

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.