I trying to display some tag informations on Tkinter interface. but i have a loop for trying to read a tag on my RFID reader and an other loop for Tkinter.
How i can update the Label in the "on_connect" function when a tag is discovered?
i have this:
from tkinter import *
import nfc
from binascii import hexlify
root = Tk()
tagId = Label(root, text=("Tag n°: " ))
tagId.grid(column=5, row=1, columnspan=3)
root.mainloop()
def on_connect(tag):
tagId['text'] = "Tag n°: " hexlify(tag.identifier).decode().upper()
def on_release(tag):
tagId['text'] = "Tag n°: "
rdwr_options = {
"targets": ("106A", "106B", "212F"),
'interval': 0.35,
"on-connect": on_connect,
"on-release": on_release,
'beep-on-connect': False,
}
if __name__ == "__main__":
with nfc.ContactlessFrontend() as clf:
if not clf.open('usb:072f:2200'):
raise RuntimeError("Failed to open NFC device.")
while True:
ret = clf.connect(rdwr=rdwr_options)
if not ret:
break
CodePudding user response:
tagId['text'] = "Tag n°: " hexlify(tag.identifier).decode().upper()
Instead of the above Syntax use the syntax present below
tagId.config(text = "Tag n°: " hexlify(tag.identifier).decode().upper())
CodePudding user response:
You could try making use of the Label
's textvariable
parameter like so
from tkinter import *
import nfc
from binascii import hexlify
root = Tk()
tag_text = StringVar() # create a variable to store the tag text
# bind that variable to your label with 'textvariable'
tagId = Label(root, textvariable=tag_text)
tag_text.set('Tag n°: ') # set your label's default text
tagId.grid(column=5, row=1, columnspan=3)
root.mainloop()
def on_connect(tag):
tag_content = hexlify(tag.identifier).decode().upper()
tag_text.set(f'Tag n°: {tag_content}')
def on_release():
tag_text.set('Tag n°:')
Whenever you call set()
on the textvariable, your tagId
label's text will be updated automatically
I do suspect, however, that the While True
infinite loop is preventing tkinter from updating. You should instead try using the tkinter after()
method to periodically call clf.connect(rdwr=rdwr_options)
at a given interval while still allowing tkinter to update your root
window
rdwr_options = {
"targets": ("106A", "106B", "212F"),
'interval': 0.35,
"on-connect": on_connect,
"on-release": on_release,
'beep-on-connect': False,
}
def read_tag(clf, rdwr_options=rdwr_options):
root.after(100, read_tag, clf) # keep calling 'read_tag' every 100mS
return clf.connect(rdwr=rdwr_options)
if __name__ == '__main__':
with nfc.ContactlessFrontend() as clf:
if not clf.open('usb:072f:2200'):
raise RuntimeError('Failed to open NFC device.')
else:
ret = read_tag(clf) # start calling 'read_tag'