Tkinter 中Variable类
Reference
- http://effbot.org/tkinterbook/variable.htm
简介
在Tkinter中一共有四种变量相关的类:
- StringVar
- IntVar
- DoubleVar
- BooleanVar
这些类定义相应的变量,去tracing和updating一些组件的值,一定变量与组件绑定之后,tracing和updating都是自动完成的,改变变量(or组件)会自动更新组件(or变量)的值。明显地,变量这对获取和设置组件的值是非常便利的。总结一些列子如下:
- 对于输入组件(Entry或spinbox)都可以通过设置其
textvariable
属性来绑定StringVar
变量和输入组件的值,这样非常方便获取输入的值,或对输入的值做合格检验。 - 对于checkButton,radiobutton和scale,可以通设置其
variable
属性来绑定四种类型的变量和这些组件的值,这样要比设置这些组件的回调函数来获取值要方便很多,变量因为绑定之后是自动更新的 - 对于label,text,button等等,这些组件,可以通过设置其
textvariable
属性来绑定StringVar
变量和其显示的文本。
方法
-
创建
var1 = StringVar() var2 = IntVar() var3 = DoubleVar()
-
set/get
## 1. 'set' var1.set("hello") var2.set(3) var3.set(3.33) ## 2. 'get' print(var1.get()) #Notes: The get method returns the current value of the variable, as a Python object. For BooleanVar variables, the returned value is 0 for false, and 1 for true. For DoubleVar variables, the returned value is a Python float. For IntVar, it’s an integer. For StringVar, it’s either an ASCII string or a Unicode string, depending on the contents.
-
trace
# 给变量绑定一个回调函数 def callback(*args): print "variable changed!" var = StringVar() var.trace("w", callback) var.set("hello") # In this example, we use the trace method to attach “observer” callbacks to the variable. The callback is called whenever the contents change:
两种形式
- trace(mode, callback) => string,which indicates the observer name
- trace_variable(mode, callback)
- The mode argument is one of “r” (call observer when variable is read by someone), “w” (call when variable is written by someone), or “u” (undefine; call when the variable is deleted).
- trace函数回返回一个字符串,即observer的名字,这个名字可以被trace_vdelete()函数用来取消监听
-
trace_vdelete
- trace_vdelete(mode, observer name)
- Remove an observer. The observer name is the string returned bytrace_variable, when the observer was first registered.
-
trace_vinfo
- trace_vinfo() =>list