修改变量值时如何处理?

时间:2018-02-10 17:16:24

标签: python tkinter

修改变量值时如何处理?

try:                        # In order to be able to import tkinter for
    import tkinter as tk    # either in python 2 or in python 3
except ImportError:
    import Tkinter as tk


def do_stuff():
    demo['text'] = var


if __name__ == '__main__':
    root = tk.Tk()
    var = "Value"
    demo = tk.Label(root, text=var)
    demo.pack()
    var = "New Value" # call do_stuff()
    tk.mainloop()

对于示例,我想在修改do_stuff时致电var

1 个答案:

答案 0 :(得分:5)

一种方法是使用变量类(BooleanVarDoubleVarIntVarStringVarVariable)及其{{1 }} 方法。这允许在修改实例所持有的值时调用方法。

trace_add

还要注意,while not always practical,一些小部件具有变量选项(变量,textvariable,list变量),允许它们保持的值与Variable类对象的值同步。下面的例子使用了:

try:                        # In order to be able to import tkinter for
    import tkinter as tk    # either in python 2 or in python 3
except ImportError:
    import Tkinter as tk


def do_stuff(*_):   # trace_add implicitly passes 3 internal arguments
    demo['text'] = var.get() # to obtain the value var holds


if __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()

另一种方法是使用对象when working with classes的属性赋值魔术方法(try: # In order to be able to import tkinter for import tkinter as tk # either in python 2 or in python 3 except ImportError: import Tkinter as tk if __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() )。

例如,每次__setattr__属性修改时,demo标签都会更新:

self.string