mfr
mfr

Reputation: 188

python Tkinter focus_set() is not working properly on capturing key press event

there are two methods in the below code, one is for capturing mouse clicks another is for the key press. I want to focus_set on the key press rather than the mouse clicks but if I use focus_set inside the key press function then it doesn't work. but if I put it inside the mouse click it works and the key functions works just fine.

from tkinter import *
root = Tk()

text = ''
frame = Frame(root, width=100, height=100)


def key(event):

    frame.focus_set() # here is the focus set which is not working
    global text

    text += event.char
    print (test)

def callback(event):
    #but If I put that same line here, it works
    print ("clicked at", event.x, event.y)

frame.bind("<Key>", key)
frame.bind("<Button-1>", callback)
frame.pack()

root.mainloop()

Upvotes: 1

Views: 1041

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386382

focus_set only affects events that fire after it is called, and it only affects keyboard events, not mouse clicks. Calling it in an event handler simply cannot effect the event being handled.

Upvotes: 2

Related Questions