Keypress Input

Terry Reedy tjreedy at udel.edu
Thu Jul 16 08:08:53 CEST 2015


On 7/15/2015 9:03 PM, Rick Johnson wrote:

> You may have solved your input capturing problem, and i
> don't think a GUI is the preferred solution for a
> graphically deficient device anyhow, but you may well need a
> GUI in the future, and this would be a fine example from which
> to learn.

This really is a nice example.  Your rationale for defining an app class 
is the best I remember seeing.

To run in 3.x, change the first two lines to

import tkinter as tk
from tkinter.messagebox import showinfo, showerror

> import Tkinter as tk
> from tkMessageBox import showinfo, showerror
>
> MSG1 = """\
> To begin retinal stimulation, press r or g or b on your keyboard
> Hold key down for extended stimulation!
> """
>
> class App(tk.Tk):
>      def __init__(self):
>          tk.Tk.__init__(self)
>          self.bind("<KeyPress>", self.evtKeyDown)
>          self.bind("<KeyRelease>", self.evtKeyUp)
>          self.protocol("WM_DELETE_WINDOW", self.evtDeleteWindow)
>          w = tk.Label(self, text=MSG1)
>          w.pack()
>          self.config(bg='white')
>          self.geometry('500x500')
>          self.focus_set()
>
>      def evtDeleteWindow(self):
>          showinfo("The window is Dying", "Goodbye cruel world!", parent=self)
>          self.destroy()
>
>      def evtKeyDown(self, event):
>          key = event.keysym.lower()
>          alert = False

>          if key == 'r':
>              self.config(bg='red')
>          elif key == 'g':
>              self.config(bg='green')
>          elif key == 'b':
>              self.config(bg='blue')
>          else:

Can condense block above to this easily extended code: (Replacing if 
if/elif/elif/... chains, when possible, is part of mastering Python.)

           try:
               self['bg'] = {'r':'red', 'g':'green', 'b':'blue'}[key]
           except KeyError:

>              msg = 'I *TOLD* you to press r or g or b, not {0!r}!'.format(key)
>              showerror('', msg, parent=self)
>
>      def evtKeyUp(self, event):
>          self.config(bg='white')
>
> if __name__ == '__main__':
>      app = App()
>      app.title('Retina Stimultor')
>      app.mainloop()
>      print "This code only executes *AFTER* the mainloop call returns!"

Adding parens to print, when there is a single object being printed, has 
no effect in 2.x and makes the statement work in 3.x.  The following 
works the same in both.

print("Mainloop has returned")

-- 
Terry Jan Reedy



More information about the Python-list mailing list