[Tkinter] [Solved]Detecting key press in gui - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: GUI (https://python-forum.io/forum-10.html) +--- Thread: [Tkinter] [Solved]Detecting key press in gui (/thread-6634.html) |
[Solved]Detecting key press in gui - Barrowman - Dec-01-2017 I am having trouble with this code: from tkinter import * root = Tk() def key(event): kp = repr(event.char) print ("pressed", kp) #repr(event.char)) if (kp == 'x'): print ("pressed x", repr(event.char)) def callback(event): frame.focus_set() print ("clicked at", event.x, event.y) frame = Frame(root, width=100, height=100) frame.bind("<Key>", key) frame.bind("<Button-1>", callback) frame.pack() root.mainloop()which is a modification of code from here: Quote:http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm The mod is the bit which I hoped would allow me to pick out a specific key so I could respond accordingly but it is ignored so I guess it's some sort of error. Can you point me in the right direction please? RE: Detecting key press in gui - Larz60+ - Dec-01-2017 works for me results: that's because I clicked in the window which makes it the widget in focus.if you issue a focus command on the Frame, you should be OK. You may also have to do a .update_idletasks()on the frame, the following from http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/universal.html Quote: w.update_idletasks() {Solved]RE: Detecting key press in gui - Barrowman - Dec-01-2017 Thanks but I did click in the window. Running my code and pressing the 'x' key gives the following: Quote:clicked at 73 43So my little 'if' test is being ignored Okay, I have found the answer here: http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/key-names.html So my 'if' test is now if(event.keycode == 82): # This time I chose to test pressing 1 on the keyboard print ("pressed 1", repr(event.char))Although I can't guess how the keycodes have been assigned RE: {Solved]RE: Detecting key press in gui - hereathome - Dec-10-2017 (Dec-01-2017, 04:19 PM)Barrowman Wrote: Although I can't guess how the keycodes have been assigned Here's the table of keysums I found with a little searching: http://www.tcl.tk/man/tcl8.4/TkCmd/keysyms.htm RE: [Solved]Detecting key press in gui - richstimson - Apr-23-2020 This works too (note use "'x'" instead of 'x') def key(event): kp = repr(event.char) print ("pressed", kp) #repr(event.char)) if (kp == "'x'"): print ("pressed x", repr(event.char))Pressing 'x' outputs:
RE: [Solved]Detecting key press in gui - Larz60+ - Apr-24-2020 richstimson - Please be aware that you are responding to a post from 2017. |