0

How can I display the letters entered from the keyboard as labels in the gui window? I can only view it on the console right now.

from tkinter import*  
from tkinter import ttk 
window = Tk()

def letter(event):
    a=str(print (repr(event.char)," key pressed."))

    label=Label(window,text=a)
    label.place(x=15,y=15)


def clicked(event):
    frame.focus_set()
    print(event.x,event.y ,"coordinate clicked.")

frame =Frame(window, width=500, height=500)
frame.bind("<Key>",letter)
frame.bind("<Button-1>", clicked) 
frame.pack()

window.mainloop()
  • Does this answer your question? [making-python-tkinter-label-widget-update](https://stackoverflow.com/questions/1918005) – stovfl May 19 '20 at 12:36

1 Answers1

0

I see a few problems with your code.

  1. What do you think str(print (repr(event.char)," key pressed.")) returns? It returns a None value which is then put into the label and the label is showing "None".

  2. In the function letter you are creating a Label every time the function is called, which means it is just overlapping the label on a label created before. So create one label outside the function and then update that label into that function.


Complete code:

from tkinter import*  
from tkinter import ttk 

window = Tk()

def letter(event):
    a = "'%s' key pressed" %event.char
    print(a)
    # Update the text of label.
    label['text'] = a

def clicked(event):
    frame.focus_set()
    print(event.x,event.y ,"coordinate clicked.")

frame =Frame(window, width=500, height=500)
frame.bind("<Key>",letter)
frame.bind("<Button-1>", clicked) 
frame.pack()

label=Label(window, text='Key')
label.place(x=15, y=15)

window.mainloop()
Saad
  • 3,340
  • 2
  • 10
  • 32
  • @murt: Happy to help. If this answer solved your issue, please mark it as accepted by clicking the outlined checkmark. – Saad May 28 '20 at 21:31