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



当我按tab键时,它会选择输入框中的所有文本,除非我将输入框multiline设置为true,但它最终会给第一篇文章一个奇怪的格式。我想tab键的行为,就像它通常在任何其他程序。当我按Shift时,我也会出现错误或大写锁定在壳里根据第一个键输入">if"语句。两个转变and大写锁定仍然可以使文本正确显示。

我试过添加一个if语句来避免tab键错误,但它似乎不起作用。我尝试使用pass和正常的print语句。

我在用什么

Python 3.7.9
  • tony IDE 3.3.4
  • 基于tkinter的Guizero .
  • ASCII表键数

Error I'm get

if ord(e.k key) == 9: #tab keyTypeError: 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属性访问,如文档中所述)。我推荐这种方法,因为append方法在末尾添加文本,没有内置的方法在当前位置插入文本,所以您最终会使用tkinter.Entryinsert方法,索引为'insert'

def select_none(event):
input_box.tk.insert('insert',' '*4)
return 'break'
input_box.tk.bind('<Tab>',select_none)

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

最新更新