焦点事件(或缺乏事件)

Focus Events (or lack thereof)

我很难理解使用 Tk 的 Python 版本 3 中条目和文本框字段的焦点事件。如果单击单选选项或按钮,我最终需要在失去焦点时验证输入框。

如果您 运行 下面的代码(仅用于演示焦点问题,而不是我在其他地方需要的验证),请将光标放在顶行输入框的任一个中,然后在其他小部件之间单击, FocusIn 和 Focus out 事件唯一一次发生在接受输入的小部件上,即 Text/Entry 个框。

单击按钮或单选选项,光标停留在条目或文本框小部件中。为什么当我明确关注单选选项或按钮时。

我已经尝试了 .bind FocusIn/Out 事件,但仍然没有成功。如果有人有解释,我很想知道为什么以及如何克服它。

from tkinter import *

root = Tk()

root.title("My Widgets")
root.update_idletasks()
root.geometry("350x200+10+300")
root.attributes("-toolwindow",1)
root.resizable(width=FALSE, height=FALSE)
root.config(bg="blue")

# function below output to the console and label the focus results
def Validate(a,b,c,d,e,f,g,h):

    text = g + ' on ' + h
    lblOutputVar.set(text)
    print(f,g,h)
    return True

var = IntVar()
lblOutputVar = StringVar()

vcmd=(root.register(Validate),'%d','%i','%P','%s','%S','%v','%V','%W')

entryOne = Entry(root, name = 'entryBoxOne')
entryOne.config(validate = 'all',vcmd=vcmd)
entryOne.grid(row=1, column=1,padx=(0,0),pady=(10,10),ipady=(1), sticky=E+W)

entryTwo = Entry(root, name = 'entryBoxTwo')
entryTwo.config(validate = 'all',vcmd=vcmd)
entryTwo.grid(row=1, column=2,padx=(10,0),pady=(10,10),ipady=(1), sticky=E+W)

txtBox = Text(root, name = 'textBox', width=10, height=1, takefocus = 0)
txtBox.grid(row=5, column=1, sticky=E+W)

aButton = Button(root, text = 'Click Me!', takefocus=1)
aButton.grid(row=5, column=2)

lblOutput = Label(root, name = 'labelOutput', width=20, height=2, textvariable=lblOutputVar)
lblOutput.grid(row=10, column=1, columnspan =2, pady=(5,0), sticky=E+W)

radioOne = Radiobutton(root, anchor = 'w', text = 'One', variable = var, value = 1, takefocus = 1)
radioOne.grid(row=2, column=1, sticky=E+W)
radioTwo = Radiobutton(root, anchor = 'w', text = 'Two', variable = var, value = 2, takefocus = 1)``
radioTwo.grid(row=3, column=1, sticky=E+W)

root.mainloop()

解释很简单,当您点击 tkinter 按钮和单选按钮时,它们没有获得焦点。如果你希望发生这种情况,你需要设置一个绑定来明确地给他们焦点。

您的另一个选择是使用 ttk 单选按钮, 获得焦点。不幸的是,两个不同的单选按钮具有不同的行为。