我很难理解Python 3中使用Tk的条目和Textbox字段的焦点事件。如果单击收音机选项或按钮,最终需要验证丢失焦点的输入框。
如果您运行下面的代码(这只用于演示焦点问题,而不是我在其他地方需要的验证),请将光标放置在顶部的行条目框中,并在其他小部件之间单击,唯一的FocusIn和焦点事件发生在接受输入(即文本/条目)框的小部件上。
单击按钮或无线电选项,光标将保留在条目或文本框小部件中。为什么,当我清楚地集中在收音机选项或按钮。
我试过.bind的焦点,但仍然没有joy。如果有人有解释的话,我会很好奇地知道为什么,可能的话,我能克服它。
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()发布于 2016-11-30 13:39:37
原因很简单,当你点击按钮和无线电按钮时,它们不会被聚焦。如果您想要这样做,您需要设置一个绑定来显式地为他们提供焦点。
您的另一个选择是使用ttk无线电按钮,它确实获得了焦点。不幸的是,这两个不同的无线电按钮有不同的行为。
https://stackoverflow.com/questions/40882390
复制相似问题