tkinter - bind keypress event to label

10,062

The label does not receive the keypress events because it does not have keyboard focus (a label does not acquire keyboard focus when clicked) so you need to give it the focus with the focus_set method:

from tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()

def prep(event):
    event.widget.config(bg='light blue')
    event.widget.focus_set()  # give keyboard focus to the label
    event.widget.bind('<Key>', edit)

def edit(event):
    print(event.char)

example = Label(frame, text='Click me')
example.pack()
example.bind('<Button-1>', prep)
mainloop()
Share:
10,062
EriktheRed
Author by

EriktheRed

Slightly obsessive python enthusiast. I spend most of my 'free' time procrastinating, working on my infamous tkinter app (which has spawned many StackOverflow questions from my side) or trawling through documentation or Overflow questions when I really should be doing a history assignment or something...

Updated on June 17, 2022

Comments

  • EriktheRed
    EriktheRed about 2 years

    If I wanted to bind a keypress event to a Label to change its text, my first reaction was to bind a buttonpress to the label, which colours the label blue, and binds a keypress to the label.
    At it's most basic, it would look like this:

    from tkinter import *
    root = Tk()
    frame = Frame(root)
    frame.pack()
    
    def prep(event):
        event.widget.config(bg='light blue')
        event.widget.bind('<Key>', edit)
    
    def edit(event):
        print(event.char)
    
    example = Label(frame, text='Click me')
    example.pack()
    example.bind('<Button-1>', prep)
    mainloop()
    

    To my surprise, the buttonpress event worked fine, colouring the label, but the keypresses afterwards did nothing. Replacing event.widget's bind with bind_all would technically solve this, but obviously this is impractical.
    Thanks guys