如何处理python guizero/tkinter中的无字母键盘输入错误?

问题描述

当我按 Tab 键时,它会选择输入框中的所有文本,除非我将输入框多行设置为 true,但它最终给第一个帖子提供了一种奇怪的格式。我希望 tab 键像在任何其他程序中一样正常工作。当我在 shell 中按 ShiftCaps lock 时,我也遇到错误 基于第一个键输入“if”语句。 ShiftCaps lock 最终仍能使文本正确显示

我已尝试添加 if 语句以避免制表键错误,但似乎不起作用。我尝试使用 pass 和普通的打印语句。

我在用什么。

我遇到的错误

if ord(e.key) == 9: #tab key 类型错误: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,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',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,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,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?',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 小部件(可以使用 {{3 }})。我会推荐这种方法而不是以前的方法,因为 tk 方法在最后添加文本,没有内置方法在当前位置插入文本,所以你最终会使用 { append 的 {1}} 方法,索引为 insert

tkinter.Entry

在函数末尾使用 'insert' 可防止其他事件处理程序被执行。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...