0

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?

user3654650
  • 5,283
  • 10
  • 27
  • 28
  • Possible duplicate of [Tkinter - Can't bind arrow key events](http://stackoverflow.com/questions/19895877/tkinter-cant-bind-arrow-key-events) – Amey Gupta Mar 11 '17 at 23:47

2 Answers2

2

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') 
1

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.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685