【问题标题】:Focus Events (or lack thereof)焦点事件(或缺乏)
【发布时间】:2016-11-30 07:15:05
【问题描述】:

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

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

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

我已经尝试了 .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()

【问题讨论】:

    标签: python tkinter textbox focus tkinter-entry


    【解决方案1】:

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

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

    【讨论】:

    • 好的,谢谢您解决这个问题。我想这只是必须绕过的那些特质之一。让我很感兴趣的是,让按钮“获取焦点”的选项可用于表单上的键盘导航,这很奇怪。
    • @DrJeep:如果您不能使用鼠标,您需要能够与按钮进行交互,唯一的方法是让按钮获得键盘焦点。这是一个可访问性的东西。我认为奇怪的是,当你点击一个类似按钮的小部件时,它会获得焦点——这是我认为 ttk 搞错的地方。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    相关资源
    最近更新 更多