python-3.x - 如何处理 python guizero/tkinter 中的无字母键盘输入错误?
问题描述
当我按下制表符时,它会选择输入框中的所有文本,除非我将输入框的多行设置为 true,但它最终会给第一个帖子一个奇怪的格式。我希望 tab 键的行为与其他程序中的正常行为一样。当我根据第一个键输入“ if ”语句的任何内容在 shell 中按Shift或Caps lock时,我也会遇到错误。Shift和Caps lock仍然最终使文本正确显示。
我尝试添加一个 if 语句来避免制表键错误,但它似乎不起作用。我尝试使用 pass 和一个普通的打印语句。
我正在使用什么。
我得到的错误
if ord(e.key) == 9: #tab key TypeError: ord() 期望一个字符,但找到长度为 0 的字符串
from guizero import *
app = App(bg='#121212',title='Virtual assistant',width=500,height=500)
box=Box(app,width='fill',height=420)
box.bg='light gray'
Spacer_box=Box(box,width='fill',height=5,align='top')
userName='Test Username: '
#A is set as the default text value to test if posting into the box works
#Setting multiline to true changes the first post format but allows for the tab key to work properly
input_box = TextBox(app,text='A',width='fill',multiline=False,align="left")
input_box.text_size=15
input_box.bg='darkgray'
input_box.text_color='black'
input_box.tk.config(highlightthickness=5,highlightcolor="black")
def key_pressed(e):
#stop tab key from highlighting text only when input_box multiline is set to true
#in the input_box above
if ord(e.key) == 9: #Tab key
print('Tab pressed')
elif ord(e.key) == 13:#Enter key
#Checks if input box is blank or only white space.
if input_box.value.isspace() or len(input_box.value)==0:
print('Empty')
input_box.clear()
else:#User's output.
Textbox=Box(box,width='fill', align='top')
Usernamers=Text(Textbox, text=userName,align='left')
Usernamers.tk.config(font=("Impact", 14))
User_Outputted_Text = Text(Textbox, text=input_box.value,size=15,align='left')
print('Contains text')
input_box.clear()
#Test responce to user
if User_Outputted_Text.value.lower()=='hi':
Reply_box=Box(box,width='fill',align='top')
Digital_AssistantName=Text(Reply_box,text='AI\'s name:',align='left')
Digital_AssistantName.tk.config(font=("Impact", 14))
Reply_text = Text(Reply_box,text='Hello, whats up?',size=15,align='left')
input_box.when_key_pressed = key_pressed
app.display()
解决方案
在函数的开头添加这个key_pressed
将消除当Caps Lock/Shift或任何返回空字符串的键被按下时的错误。
if e.key=='':
return
以下已阻止Tab密钥选择文本
if ord(e.key) == 9: #Tab key
print('Tab pressed')
input_box.append(' '*4)
input_box.disable()
input_box.after(1,input_box.enable)
基本上我已经禁用了小部件,然后在1
毫秒后启用它。
更新
另一种方法可能是将Tab密钥绑定到Entry
内部使用的小部件(可以使用文档tk
中所述的属性访问)。我会推荐这种方法而不是以前的方法,因为该方法在末尾添加文本,没有内置方法可以在当前位置插入文本,所以你最终会使用index as的方法.append
insert
tkinter.Entry
'insert'
def select_none(event):
input_box.tk.insert('insert',' '*4)
return 'break'
input_box.tk.bind('<Tab>',select_none)
在函数末尾使用return 'break'
可防止执行其他事件处理程序。
推荐阅读
- swift - 更改内容顺序时,SwiftUI MacOS 列表布局出现故障
- javascript - Angular Material 选项 - 硬编码值有效,动态返回值无效
- android - Android应用程序图标点击需要太多时间才能打开
- javascript - 我的 Angular 11 cli 应用程序无法与 jest 一起使用。我得到的错误:TypeError:无法读取未定义的属性“路径”
- ios - 如何将数据发布到 CKRecord Fields objc
- ios - 检查自动续订订阅是否仍然有效?斯威夫特 5
- c++ - 如何在课堂上模板化 2D 容器?
- jquery - 为什么角度数据表不呈现?
- android - 信号 11 (SIGSEGV),代码 1 (SEGV_MAPERR)-android 10 (API 29)
- android - 发布前报告,试图从 JVM 回溯追踪 kotlin API 错误