python Tkinter Capturing keyboard events save as one single string

Home / Uncategorized / python Tkinter Capturing keyboard events save as one single string

Question:
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)
frame.bind("", callback)
frame.pack()

root.mainloop()


Answer:
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)
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *