L'input chiave è un evento predefinito. È possibile prendere eventi collegando event_sequence
(s) a event_handle
(s) utilizzando uno o più dei metodi di associazione esistenti (bind
, bind_class
, tag_bind
, bind_all
). Per fare questo:
- definire un
event_handle
metodo
- scegliere un evento (
event_sequence
) che misura il vostro caso da an events list
Quando un evento si verifica, tutti questi metodi di rilegatura chiama implicitamente il Metodo event_handle
mentre si passa un oggetto Event
, che include le informazioni sulle specifiche dell'evento che si è verificato, come argomento.
Per rilevare l'input della chiave, è possibile prima prendere tutti gli eventi '<KeyPress>'
o '<KeyRelease>'
e quindi individuare la chiave specifica utilizzata utilizzando l'attributo event.keysym
.
Di seguito è un esempio usando bind
di catturare sia '<KeyPress>'
e '<KeyRelease>'
eventi in una particolare widget (root
):
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
def event_handle(event):
# Replace the window's title with event.type: input key
root.title("{}: {}".format(str(event.type), event.keysym))
if __name__ == '__main__':
root = tk.Tk()
event_sequence = '<KeyPress>'
root.bind(event_sequence, event_handle)
root.bind('<KeyRelease>', event_handle)
root.mainloop()
costa usare Tk richiede una finestra grafica? Sto lavorando su un sistema embedded. il sys.strin.read() di seguito è allettante, ma è necessario premere invio. – user391339
@ user391339: Penso che Tk richiederebbe un sistema di finestre o un display virtuale. Per un sistema embedded, una ricetta 'getch' come [questa] (http://stackoverflow.com/a/21659588/190597) potrebbe essere migliore. – unutbu
Si noti che questo funziona solo in Python 3.x. –