Python Tkinter Canvas fail to bind keyboard

前端 未结 3 1959
刺人心
刺人心 2020-12-04 01:22

I\'ve been running a small script like this

from Tkinter import *
root = Tk()
def callback(event):
    print \"callback\"
w = Canvas(root, width=300, height         


        
3条回答
  •  伪装坚强ぢ
    2020-12-04 02:20

    There is a handy event in tkinter called "Enter", that tracks when the mouse enters a widget. If you bind it to the canvas, and in the binding's callback for that event you canvas.focus_set, then whenever the mouse is on the canvas you will have focus, and thus the keyboard bindings will work.

    This will work even if the canvas looses focus (say through entering text in another widget), because when the mouse enters again the canvas, it will regain focus.

提交回复
热议问题