Python 当向下箭头单击小部件组合时调用focus_get()时出现异常键错误
尝试通过以下代码查看焦点的位置,但当在小部件组合上单击向下箭头时,如果调用Python 当向下箭头单击小部件组合时调用focus_get()时出现异常键错误,python,tkinter,Python,Tkinter,尝试通过以下代码查看焦点的位置,但当在小部件组合上单击向下箭头时,如果调用focus\u get(),则会出现异常KeyError 将tkinter作为tk导入 从tkinter导入ttk def show_focus(): configure(text=f'focusat{root.Focus\u get()}') root.after(100,显示焦点) 字体=('Courier New',16) root=tk.tk() label=tk.label(根,text='Focus at',w
focus\u get()
,则会出现异常KeyError
将tkinter作为tk导入
从tkinter导入ttk
def show_focus():
configure(text=f'focusat{root.Focus\u get()}')
root.after(100,显示焦点)
字体=('Courier New',16)
root=tk.tk()
label=tk.label(根,text='Focus at',width=40,font=font,anchor='w')
标签包装(锚定=w',填充=x')
value1=tk.StringVar()
值1.设置(“条目”)
entry=tk.entry(root,textvariable=value1,width=40,font=font,bg='green',fg='black')
入口包装(锚定=w',填充=x')
value2=tk.StringVar()
值2.设置(“男性”)
combo=ttk.Combobox(根,值=['Male','Female',textvariable=value2,宽度=40,高度=5,字体=font)
组合包(anchor='w')
显示焦点()
root.mainloop()
Tkinter回调中出现异常
回溯(最近一次呼叫最后一次):
文件“C:\Software\Python\lib\tkinter\\ uuuuuu init\uuuuuu.py”,第1892行,在调用中__
返回self.func(*args)
文件“C:\Software\Python\lib\tkinter\\ uuuuu init\uuuuuuu.py”,第814行,在callit中
func(*args)
文件“D:\tkinter focus\u get.py”,第5行,在show\u focus中
configure(text=f'focusat{root.Focus\u get()}')
文件“C:\Software\Python\lib\tkinter\\ uuuuu init\uuuuu.py”,第758行,处于焦点位置
返回self.\u nametWidget(名称)
文件“C:\Software\Python\lib\tkinter\\uuuuu init\uuuuuu.py”,第1507行,名称为Widget
w=w.儿童[n]
KeyError:“弹出窗口”
在tkinter的方法focus\u get()
中
。。。
name=self.tk.call('focus')#name:
...
self.\u nametowidget(名称)
...
def nametowidget(自身,名称):
“”“返回由标识的小部件的Tkinter实例。”
它的Tcl名称。”“”
name=str(name).split('.'))
w=自我
如果不是名称[0]:
w=w._根()
名称=名称[1:]
对于名称中的n:
如果不是n:
打破
孩子们!combobox'在root.children中,但“poppdown”不在combo.children中,因此它在这里得到KeyError。
返回w
_nametowidget=nametowidget
我的问题是,我如何才能找到重点,但要避免这种情况。也许try-except
语句可以跳过异常,但此时它会得到错误的焦点
[更新]
def show_focus():
尝试:
configure(text=f'focusat{root.Focus\u get()}')
除:
#在(100,show_focus)之后,如果该语句放在这里,如果没有异常,该函数将停止
通过
root.after(100,show_focus)#语句在此处保持焦点所在位置的更新
您可以通过忽略每次按下“弹出”按钮来克服错误
def show_focus():
if str(root.tk.call(combo,'state')) != 'pressed':
label.configure(text=f'Focus at {root.focus_get()}')
else:
label.configure(text=f'Focus at {str(combo)}')
root.after(100, show_focus)
这是一种解决问题的方法,因为“弹出”按钮不是由
nametWidget()
标识的(使用focus\u get()
时用于返回小部件名称)。我在上发现了一个类似的错误,可能是因为“下拉按钮”对nametowidget()
无效。关于尝试/除外
:将根放在(…)
内部除外。将根放在(…)内部除外代码>,当出现异常时,它将停止更新焦点所在的位置。当方法focus\u的某些条件得到时,似乎有一个bug。不,不会。只要你点击其他地方而不是在帖子中点击弹出按钮更新。更新的代码有什么问题吗。它向我显示了正确的焦点。