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

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()
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, networking, learning, and sharing knowledge.