[New-bugs-announce] [issue33335] turtle.onkey doesn't pass key information when key is None
report at bugs.python.org
Sun Apr 22 14:34:36 EDT 2018
New submission from J E <jepst79 at gmail.com>:
I use the turtle module to teach Python to university students. The turtle.onkey function allows a program to register a callback function to handle a keyboard when the turtle window has a focus. For example, this call will result in myfun() getting called when the "s" key is pressed:
print("You pressed s")
But what if I want to handle all keys? I could create a bunch of functions, and register a separate callback for each possible; that's not a great solution. A better solution is to let turtle call a single function when any key is pressed. Fortunately, this is possible by passing None in for the key:
print("You pressed some key")
However: there is no way for myfun to determine which key was pressed. It is called with no parameters, and has no way to recover information about which key was pressed, so this approach is useless. The only way to handle all keyboard events it to call onkey, with a separate handler, for every key you potentially want to handle.
>From the source  this looks like it was intended that when key is None, turtle would pass a Tkinter event to the handler, so that it could recover information about the event, but this doesn't happen.
I would argue that correct behavior is not to expose Tkinter event to users of the higher-level turtle library, but rather to pass the name of the key as a string parameter, so you could write this:
print("You pressed "+key)
This is an easy fix and I'd be happy to submit a patch.
title: turtle.onkey doesn't pass key information when key is None
versions: Python 2.7, Python 3.4, Python 3.5, Python 3.6, Python 3.7, Python 3.8
Python tracker <report at bugs.python.org>
More information about the New-bugs-announce