我是一名教师,正在编写一个程序,为迟到的学生阅读8位数的身份证条码。我是一名经验丰富的程序员,但对Python很新,对Tkinter很新(大约36小时的经验)到目前为止我已经大量使用了这个网站,但我一直无法找到这个问题的答案:
如何准确读取8位数字,并立即在文本框中显示这8位数字。我可以做7,但似乎无法达到8.有时,我在文本框中什么也得不到。我已经使用了Entry,bind,并且一切正常,除了我似乎无法在绑定事件中读取键以将键一致地放置在输入的文本框中。当我打印它时,ID似乎总是正确的,但在文本框中它是不正确的。我似乎无法显示tkinter屏幕,因此在完成后它只显示7位数字或文本框中没有任何内容。
以下是我的代码片段,用于处理GUI
from tkinter import *
from collections import Counter
import time
i=0
class studentNumGUI():
def __init__(self, master):
master.title("Student ID Reader")
self.idScanned = StringVar()
localTime = time.asctime(time.localtime(time.time()))
self.lblTime = Label(master, text=localTime)
self.lblTime.pack()
self.lbl = Label(master, text="Enter Student ID:")
self.lbl.pack()
self.idScanned.set("")
self.idScan = Entry(master,textvariable=self.idScanned,width=12)
self.idScan.pack()
self.frame=Frame(width=400,height=400)
self.frame.pack()
self.frame.focus()
self.frame.bind('<Key>',self.key)
def key(self,event):
global i
self.frame.focus()
self.idScan.insert(END,event.char)
print(repr(event.char)," was pressed") #just to make sure that my keystrokes are accepted
if (i < 7):
i += 1
else:
#put my other python function calls here once I fix my problem
self.frame.after(2000)
#self.idScan.delete(0,END) #Then go blank for the next ID to be read
i=0
root = Tk()
nameGUI = studentNumGUI(root)
root.mainloop()
答案 0 :(得分:0)
您正在做一些不寻常的事情,以便根据按键将文本放入Entry字段中。我已经更改了你的代码,以便它将焦点设置在Entry小部件上,并且每次按下一个键时都会检查Entry字段的内容(当Entry有焦点时)。然后我获取Entry字段的内容并检查长度是否小于8.如果它是8(或更大),它将清除该框。 这对你有什么用? 我已经留下了注释掉的代码
from tkinter import *
from collections import Counter
import time
class studentNumGUI():
def __init__(self, master):
master.title("Student ID Reader")
self.idScanned = StringVar()
localTime = time.asctime(time.localtime(time.time()))
self.lblTime = Label(master, text=localTime)
self.lblTime.pack()
self.lbl = Label(master, text="Enter Student ID:")
self.lbl.pack()
self.idScanned.set("")
self.idScan = Entry(master,textvariable=self.idScanned,width=12)
self.idScan.pack()
self.idScan.focus_set()
self.frame=Frame(width=400,height=400)
self.frame.pack()
#self.frame.focus()
#self.frame.bind('<Key>',self.key)
self.idScan.bind('<Key>',self.key)
def key(self,event):
#self.frame.focus()
#self.idScan.insert(END,event.char)
print(repr(event.char)," was pressed") #just to make sure that my keystrokes are accepted
len(self.idScanned.get())
if (len(self.idScanned.get())<8):
pass
else:
#put my other python function calls here once I fix my problem
self.idScan.delete(0,END) #Then go blank for the next ID to be read
#self.frame.after(2000)
root = Tk()
nameGUI = studentNumGUI(root)
root.mainloop()