Binding keys to keyboard events. : Key Event « Tkinker « Python Tutorial






Binding keys to keyboard events.
from Tkinter import *

class KeyDemo( Frame ):
   def __init__( self ):
      Frame.__init__( self )
      self.pack( expand = YES, fill = BOTH )
      self.master.title( "Demonstrating Keystroke Events" )
      self.master.geometry( "350x50" )

      self.message1 = StringVar()
      self.line1 = Label( self, textvariable = self.message1 )
      self.message1.set( "Type any key or shift" )
      self.line1.pack()

      self.message2 = StringVar()
      self.line2 = Label( self, textvariable = self.message2 )
      self.message2.set( "" )
      self.line2.pack()

      self.master.bind( "<KeyPress>", self.keyPressed )
      self.master.bind( "<KeyRelease>", self.keyReleased )

      self.master.bind( "<KeyPress-Shift_L>", self.shiftPressed )
      self.master.bind( "<KeyRelease-Shift_L>",
         self.shiftReleased )

   def keyPressed( self, event ):
      self.message1.set( "Key pressed: " + event.char )

   def keyReleased( self, event ):
      self.message1.set( "Key released: " + event.char )
   
   def shiftPressed( self, event ):
      self.message1.set( "Shift pressed" )

   def shiftReleased( self, event ):
      self.message1.set( "Shift released" )
   
KeyDemo().mainloop()








18.16.Key Event
18.16.1.Get key codeGet key code
18.16.2.Up arrow keyUp arrow key
18.16.3.Enter key eventEnter key event
18.16.4.Bind key action to buttonBind key action to button
18.16.5.Entry components and event binding demonstration.Entry components and event binding demonstration.
18.16.6.Binding keys to keyboard events.Binding keys to keyboard events.