我很难理解使用Tk在Python版本3中的Entry和Textbox字段的焦点事件。如果我点击一个收音机选项或按钮,我最终需要验证丢失焦点的输入框。
如果您运行下面的代码(仅用于演示Focus问题而不是我在其他地方需要的验证),请将光标放在任一顶行条目框中,然后在其他小部件之间单击,这是FocusIn和Focus唯一的时间out事件发生在接受输入的小部件上,即文本/输入框。
单击按钮或单选按钮,光标将保留在Entry或Textbox小部件中。为什么我明确专注于收音机选项或按钮。
我尝试过.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()
答案 0 :(得分:0)
解释很简单,当你点击它们时,tkinter按钮和radiobutton没有给定焦点。如果您希望这种情况发生,您需要设置一个绑定来明确地为它们提供焦点。
您的另一个选择是使用 获得焦点的ttk radiobutton。不幸的是,两个不同的radiobutton具有不同的行为。