user3654650
user3654650

Reputation: 6103

Key binding does not work in tkinter

I made simple script:

from tkinter import *


class MyFrame(Frame):
    def __init__(self, parent = None):
        Frame.__init__(self, parent, bg = 'red')                
        self.pack(fill=BOTH, expand=YES)

        self.bind('<Key>', lambda e: print("pressed any key"))



root = Tk()
root.geometry("300x200")
f = MyFrame(root)
root.mainloop()

But binding for pressing any key do not work. Nothing happens whey I press any key. Do you know why?

Upvotes: 0

Views: 2027

Answers (2)

Bryan Oakley
Bryan Oakley

Reputation: 385970

The reason the binding didn't seem to work is that the frame that you attached the binding to didn't have keyboard focus. Only the widget with keyboard focus will react to the binding. It's perfectly acceptable to do what you did and bind to a frame, you just need to make sure that the widget you bind to gets the keyboard focus.

There are at least two solutions: give the frame the keyboard focus (with the focus_set method), or put the binding on the main window which is what initially gets the keyboard focus.

Upvotes: 1

user2555451
user2555451

Reputation:

You need to call the bind method of parent, which is a reference to the tkinter.Tk instance that represents the main window:

parent.bind('<Key>', lambda e: print("pressed any key"))

self.bind is calling the bind method of the tkinter.Frame instance created when you did:

Frame.__init__(self, parent, bg = 'red') 

Upvotes: 2

Related Questions