Tkinter Keyboard and mouse event binding pitfalls
Frame itself is a Widget control, you need to be especially careful about the concept of getting focus when using frame, when the event binding is related to Frame, the keyboard binding can take effect only when Frame gets focus.
Example
Application of keyboard and mouse binding Frame objects.
from tkinter import *
def key(event): # Handle keyboard press a-z events
print("Press " + repr(event.char) + " key")
def coordXY(event):
frame.focus_set()
print("Mouse position:",event.x,event.y)
root = Tk()
root.title("apidemos.com")
frame = Frame(root,width=100,height=100)
frame.bind("<Key>",key)
frame.bind("<Button-1>",coordXY)
frame.pack()
root.mainloop()
Output:
This program must be executed with the mouse cursor inside the window and a mouse click first, at which point line 6 simultaneously uses frame.focus_set( ) to give the Widget control frame the focus before the keystroke can be acted upon.
The following is a demonstration of the output screen.
The reason for executing the program at the beginning is that it is bound to the root window, which has the focus when the program is started.