Tkinter keyboard binding basic usage
Tkinter keyboard binding basic usage Example#1
This is a test keyboard binding program, in the execution of the window will appear, if you press the Esc key, a dialog box will appear asking whether to leave, click the "Yes" button to leave the program, click the "No" button to continue the program.
from tkinter import *
from tkinter import messagebox
def leave(event): # <Esc> Event Handler
ret = messagebox.askyesno("apidemos dialog...","Are you leaving?")
if ret:
root.destroy()
else:
return
root = Tk()
root.title("apidemos.com")
root.bind("<Escape>",leave) #<Enter> <Return> <Escape> <a> <A>
lab = Label(root,text="Test Esc key",
bg="yellow",fg="blue",
height=4, width=15,
font="Times 12 bold")
lab.pack(padx=30,pady=30)
root.mainloop()
Output:
Tkinter keyboard binding basic usage Example#2
This program is executed with <Key>
as the binding event key, and the whole program will print out the a … z keys pressed. Line 4 of this program uses the lesser-used repr( ) function, which handles the arguments as strings.
from tkinter import *
def key(event): # Handle keyboard press a-z key events
print("Press " + repr(event.char) + " Key")
root = Tk()
root.title("apidemos.com")
root.bind("<Key>",key) # <Key> key binding key function
root.mainloop()
Output:
Below is a clicked apidemos.com result: