I'm writing the program for a psychology experiment that requires participants to learn a new number pad mapping.
If the keys were letters it would be easy enough: a=1
, b=2
, c=3
etc.
But apparently Python doesn't allow mapping to integers. Hmm.
A partial solution could be to use a dictionary, such as:
newdict = {'1': 9, '2': 8, '3': 7}
However, participants will be typing into a text box, and when their entry appears in the box it needs to have been converted already. There is no clear way to apply the newdict['1']
call.
How can this remapping be accomplished?
Your instinct to use a dict is good -- it's an easy way to create a mapping from one character to another. You could also just use a list of tuples (eg: ((1, 9), (2, 8), ...)
)
You don't mention the GUI toolkit (or whether you're just doing a console app), so I'll give a tkinter example to illustrate how to set up a key binding for each key using the dictionary. Using a tuple would be nearly identical.
import tkinter as tk # for python 2 use 'Tkinter'
class Example(tk.Frame):
keymap = {'1': '9', '2': '8', '3': '7',
'4': '6', '5': '5', '6': '4',
'7': '3', '8': '2', '9': '1'}
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.entry = tk.Entry(self, width=20)
self.entry.pack(fill="x", pady=20, padx=20)
for old_key, replacement in self.keymap.items():
self.entry.bind('<KeyPress-%s>' % old_key,
lambda event, char=replacement: self.insert(char))
def insert(self, char):
self.entry.insert("insert", char)
return "break"
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.