Reputation: 87
Maybe I have titled my question correctly. To explain:
I have a USB barcode scanner that I have hooked up to a RPI2 and I can scan barcodes that will place the 12 digits into a terminal (example 070038348184) with a click of the barcode scanner trigger button. This verifies to me the barcode scanner and the RPI2 can interact with one another. With that said, I am trying to write a Tkinter/Python script to get input from this scanner without using an entry widget. The nature of this project does not have a keyboard, just a touchscreen. So using a entry and button widget to get the barcode scan stored into a variable is what I would like to avoid. I have did some research, but not able to discern any clear cut solution. Finally, I would like to be able to pull the trigger on the scanner and grab the digits from the terminal and store them into a variable for use in the Tkinter/Python script. Any suggestions would be appreciated.
Upvotes: 3
Views: 2388
Reputation: 142651
As I understand this scanner works as keyboard - it sends keys presses directly to program - so maybe try to use bind('<Key>', callback)
to catch all keypresses.
import tkinter as tk
from tkinter.messagebox import showinfo
def get_key(event):
global code
if event.char in '0123456789':
code += event.char
#print('>', code)
label['text'] = code
elif event.keysym == 'Return':
#print('result:', code)
showinfo('Code', code)
# --- main ---
root = tk.Tk()
root.geometry('100x20')
# global variables
code = ''
label = tk.Label(root, text="?")
label.pack()
root.bind('<Key>', get_key)
root.mainloop()
EDIT: as you asked - the same in class
import tkinter as tk
from tkinter.messagebox import showinfo
class Window(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.geometry('100x20')
self.code = ''
self.label = tk.Label(self, text="?")
self.label.pack()
self.bind('<Key>', self.get_key)
def get_key(self, event):
if event.char in '0123456789':
self.code += event.char
#print('>', self.code)
self.label['text'] = self.code
elif event.keysym == 'Return':
#print('result:', self.code)
showinfo('Code', self.code)
# --- main ---
win = Window()
win.mainloop()
#Window().mainloop()
Upvotes: 2