tkinter - bind keypress event to label

EriktheRed

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

j_4321

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()

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related