该脚本旨在读取二维码,这样用户就不必按Enter键,也不必按任何按钮。 我正在逐字符读取二维码;它包含一个“.”来表示字符串的结尾,例如:“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()
问题是您的
<Key>
绑定发生在小部件的默认操作之前(即:字符实际插入到小部件之前)。在一个简单的解决方案是绑定到
<KeyRelease>
,这为默认操作(绑定到<KeyPress>
)提供了在自定义代码之前完全处理的机会。在有关如何处理事件的更彻底的解释,请参阅以下答案:Basic query regarding bindtags in tkinter
相关问题 更多 >
编程相关推荐