mfr
mfr

Reputation: 188

python Tkinter Capturing keyboard events save as one single string

is it possible to store keyboard events into one string? with the code below it only stores one char and prints it. but for a card reader or bar code reader, it contains a collection of character/ string not one character at a time. The goal is the save all the char pressed into text variable.

from tkinter import *

root = Tk()

def key(event):
     text= event.char
     text+= event.char
     print ("pressed", text)

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

frame = Frame(root, width=100, height=100)
frame.bind("<Key>", key)
frame.bind("<Button-1>", callback)
frame.pack()

root.mainloop()

Upvotes: 2

Views: 1149

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 91007

Currently, you are creating text variable , everytime the key() function gets called, and text it only stores the last character you typed.

You can define text as a module level variable , and use that module level text inside your key function -

text = ''
def key(event):
    global text
    text+= event.char
    print("pressed", text)

Upvotes: 2

Related Questions