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.
Tkinter for console getkey, Pause/Restart/Quit
""" 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()
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.