Outside tkinter I do not know of a way to get and respond to a single keystroke. Inside tkinter the code below does it while providing examples of binding, focus, configure, update, and lots of other stuff.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | import tkinter as tk from tkinter import * import sys import time root = tk.Tk() root.geometry( "1024x768" ) msg = StringVar() msg. set ( "Keypress Response Demo: press a key, 'Enter' to exit." ) def respond( self ): # keypress=repr(self.char) msg. set ( "keypress registered! input was: " + self .char + ", ascii: " + str ( ord ( self .char))) def ifreturn( self ): if int ( ord ( self .char)) = = 13 : msg. set ( "Return/enter keypress dectected. App closing in 3 seconds" ) root.update() time.sleep( 2 ) l1.configure(relief = 'flat' ) root.update for i in range ( 3 , 0 , - 1 ): msg. set ( str (i)) root.update() time.sleep( 1 ) root.destroy() sys.exit l1 = tk.Label(takefocus = 1 , textvariable = msg, font = ( 'Verdana' , 20 , 'bold' ), pady = 330 , bd = 10 , relief = 'groove' ) l1.pack() l1.bind( "<Key>" , respond) l1.bind( '<Return>' , ifreturn) l1.focus_set() root.mainloop() |