修改变量值时该怎么办?

修改变量值时该怎么办?,第1张

修改变量值时该怎么办?

一种方法利用可变类(的

BooleanVar
DoubleVar
IntVar
StringVar
Variable
),以及它们的
trace_add
方法。当实例拥有的值被修改时,它允许调用一个方法。

try:  # In order to be able to import tkinter for    import tkinter as tk    # either in python 2 or in python 3except importError:    import Tkinter as tkdef do_stuff(*_):   # trace_add implicitly passes 3 internal arguments    demo['text'] = var.get() # to obtain the value var holdsif __name__ == '__main__':    root = tk.Tk()    var = tk.StringVar(value="Value")    #var = tk.BooleanVar(value=True)    #var = tk.DoubleVar(value=2.78)    #var = tk.IntVar(value=0)    #var = tk.Variable(value=["Value", True, 2.78, 0])    demo = tk.Label(root, text=var.get())    demo.pack()    var.trace_add('write', do_stuff)    # call do_stuff when var is set    var.set("New Value")    # to replace the value var holds    #var.set(False)    #var.set(3.14)    #var.set(42)    #var.set(["New Value", False, 3.14, 42])    tk.mainloop()

还需要注意的是,尽管并非总是实用,但某些小部件具有变量选项(变量,文本变量,列表变量),这些选项允许它们持有的值与变量类对象的值同步。下面的示例利用了这一点:

try:  # In order to be able to import tkinter for    import tkinter as tk    # either in python 2 or in python 3except importError:    import Tkinter as tkif __name__ == '__main__':    root = tk.Tk()    var = tk.StringVar(value="Value")    demo = tk.Label(root, textvariable=var)    demo.pack()    var.set("New Value")    # label is in sync right-away    tk.mainloop()

另一种方法是在使用class时

__setattr__
利用对象的属性分配魔术方法。

例如,

demo
标签将在每次
self.string
修改属性时更新:

try:  # In order to be able to import tkinter for    import tkinter as tk    # either in python 2 or in python 3except importError:    import Tkinter as tkclass MyLabel(tk.Label):    def __init__(self, master, var="", *args, **kwargs):        tk.Label.__init__(self, master, *args, **kwargs)        self.var = var    def __setattr__(self, name, value):        self.__dict__[name] = value        if name == 'var': self.do_stuff()    def do_stuff(self):        self['text'] = self.varif __name__ == '__main__':    root = tk.Tk()    demo = MyLabel(root, "Value")    demo.pack()    demo.var = "New Value"    tk.mainloop()


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5675030.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存