该脚本旨在读取QR码,因此用户无需按Enter键,也无需按任何按钮。 我按字符阅读qr-code字符;它包含一个"。"表示字符串的结尾,如:" 012-ABCDE。" 即使连续使用并且点仍在条目中,脚本也能正常工作。请有人帮我消除那个点吗?
import tkinter as tk
import string
class mainWindow(tk.Frame):
def __init__(self, controller):
askForQRCode(self, controller)
def processQRCode(self, qrCode):
print('processing QR code {}'.format(qrCode))
class askForQRCode(tk.Frame):
def __init__(self, parent, controller):
self.parent = parent
self.givenString = ''
#PANEL QR CODE
panelQRCode = tk.PanedWindow(controller)
panelQRCode.pack(fill='both', padx=7)
# ...
#SUBJECT
fSubject = tk.LabelFrame(panelQRCode, text='Subject ID')
panelQRCode.add(fSubject, stretch='always')
label = tk.Label(fSubject, text='QR Code')
label.grid(column=0, columnspan=2, row=1)
self.qrCodeEntry = tk.Entry(fSubject)
self.qrCodeEntry.grid(column=0, columnspan=2, row=3, padx=7)
self.qrCodeEntry.focus_force()
self.qrCodeEntry.bind('<Key>', self.onQREntry)
def onQREntry(self, event):
theChar = event.char.upper()
list1 = list(string.ascii_uppercase)
list2 = ['-','0','1','2','3','4','5','6','7','8','9']
if theChar in list1 or theChar in list2:
self.givenString = self.givenString + theChar
elif theChar == '.':
self.qrCodeEntry.delete(0, tk.END)
self.parent.processQRCode(self.givenString)
if __name__ == '__main__':
root = tk.Tk()
root.title('dummy')
theMainWindow = mainWindow(root)
root.mainloop()
答案 0 :(得分:1)
问题是你的<Key>
绑定发生在窗口小部件的默认操作之前(即:在字符实际插入窗口小部件之前)。
一个简单的解决方案是绑定到<KeyRelease>
,这使得默认操作(绑定到<KeyPress>
)有机会在自定义代码之前完全处理。
有关如何处理事件的更全面说明,请参阅以下答案:Basic query regarding bindtags in tkinter