如何检测 OptionMenu 或 Checkbutton 何时更改?

编程入门 行业动态 更新时间:2024-10-26 03:32:34
本文介绍了如何检测 OptionMenu 或 Checkbutton 何时更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我的 tkinter 应用程序有多个控件,我想知道它们何时发生任何更改,以便我可以更新应用程序的其他部分.

My tkinter application has several controls, and I'd like to know when any changes occur to them so that I can update other parts of the application.

除了编写更新程序函数并在结尾处循环之外,还有什么我可以做的:

Is there anything that I can do short of writing an updater function, and looping at the end with:

root.after(0, updaterfunction) 

这种方法过去有用,但如果要检查的东西很多,恐怕成本会很高.

This method has worked in the past but I'm afraid that it might be expensive if there are many things to check on.

即使我确实使用了这种方法,我是否可以通过仅更新具有更改变量的项目来节省资源?如果是这样,请分享方法,因为我不确定如何检测更新功能之外的特定更改.

Even if I did use this method, could I save resources by only updating items with changed variables? If so, please share how, as I'm not sure how to detect specific changes outside of the update function.

推荐答案

许多 tkinter 控件可以与一个变量相关联.对于那些您可以在变量上放置跟踪的人,以便在变量更改时调用某些函数.

Many tkinter controls can be associated with a variable. For those you can put a trace on the variable so that some function gets called whenever the variable changes.

示例:

在以下示例中,无论变量如何更改,只要变量发生变化,就会调用回调.

In the following example the callback will be called whenever the variable changes, regardless of how it is changed.

def callback(*args):
    print(f"the variable has changed to '{var.get()}'")

root = tk.Tk()
var = tk.StringVar(value="one")
var.trace("w", callback)

有关传递给回调的参数的更多信息,请参阅此答案

For more information about the arguments that are passed to the callback see this answer

这篇关于如何检测 OptionMenu 或 Checkbutton 何时更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 08:20:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1391336.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:OptionMenu   Checkbutton

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!