小部件的值更改事件类型或使用 .trace_variable() 技术?
对于数据输入小部件(例如 Entry、Text、Spinner、Checkbutton、Radiobutton)是否存在值更改类型的事件?通过值更改,我的意思是能够检测到小部件的值何时由于键盘输入或剪切/删除/粘贴(和文本 edit_undo/edit_redo)活动而发生更改?我在 Tkinter 事件文档 [1] 中没有看到此类事件的描述。
将 Tkinter 变量链接到我想要监视的小部件值并使用这些变量的 .trace_variable( 'w', ... ) 方法绑定到值更改是否是正确的技术?这似乎是正确的方法,但我在我研究过的 Tkinter 应用程序源代码中没有看到大量使用 trace_variable() ...导致我对使用这种方法持谨慎态度。
[1] http://infohost.nmt.edu/tcc/help/ pubs/tkinter/events.html
Is there an on-value-change type of event for data input widgets like Entry, Text, Spinner, Checkbutton, Radiobutton? By on-value-change, I mean the ability to detect when the value of a widget has changed due to keyboard input or cut/delete/paste (and Text edit_undo/edit_redo) activity? I see no such event described in the Tkinter event documentation [1].
Is the proper technique to link Tkinter variables to widget values I want to monitor and use these variables' .trace_variable( 'w', ... ) methods to bind to value changes? This seems like the right approach, but I haven't seen a lot of trace_variable() use in the Tkinter application source code that I've studied ... leading me to be cautious about using this approach.
[1] http://infohost.nmt.edu/tcc/help/pubs/tkinter/events.html
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不同的小部件需要不同的解决方案。例如,检查按钮和单选按钮有一个命令选项,并且通过输入小部件,您可以使用内置的验证功能。
对于所有可以绑定到变量的小部件,进行变量跟踪是一种常见的解决方案。文本小部件是一个例外,因为您不费很大力气就无法将其与变量关联起来。
在 tcl/tk 世界中,我将所有小部件关联到单个数组(tcl 的哈希映射/字典名称),然后在该数组上放置单个跟踪。不幸的是 tkinter 不直接支持 tcl 数组。但是,支持有点容易入侵。有关更多信息,请参阅我对此问题的回答:如何在 Tkinter 小部件值更改时运行代码?
Different widgets call for different solutions. For example, check buttons and radio buttons have a command option, and with an entry widget you can use the built-in validation features.
For all the widgets that can be tied to a variable, doing a variable trace is a common solution. The text widget is one exception since you can't associate it with a variable without a lot of effort.
In the tcl/tk world I associate all my widgets to a single array (tcl's name for a hash map / dictionary) and then put a single trace on the array. Unfortunately tkinter doesn't directly support tcl arrays. However, support is somewhat easy to hack in. For more information see my response to this question: How to run a code whenever a Tkinter widget value changes?