Tkinter:Checkbutton

来源:互联网 发布:输入法 linux 编辑:程序博客网 时间:2024/05/20 23:06

第一个Checkbutton 例子

Checkbutton 又称为多选按钮,可以表示两种状态:On 和Off,可以设置回调函数,每当
点击此按钮时回调函数被调用

from Tkinter import *
root = Tk()
Checkbutton(root,text = 'python').pack()
root.mainloop()

效果:

设置Checkbutton的时间处理函数

# command:指定事件处理函数
from Tkinter import *
def callCheckbutton():
         print 'you check this button'
root = Tk()
# 指定事件处理函数
Checkbutton(root,text = 'check python',command = callCheckbutton).pack()
root.mainloop()
# 不管Checkbutton 的状态如何,此回调函数都会被调用

将变量与Checkbutton 绑定

此列是显示选定状态值

variable:指定与Checkbutton 绑定的变量,显示Checkbutton 的值。

将一整数与Checkbutton 的值绑定,每次点击Checkbutton,将打印出当前的值。

from Tkinter import *
root = Tk()

v = IntVar()
def callCheckbutton():
      print v.get()

Checkbutton(root,variable = v,text = 'checkbutton value',command = callCheckbutton).pack()
root.mainloop()

上述的textvariable 使用方法与Button 的用法完全相同,使用此例是为了区别Checkbutton
的另外的一个属性variable,此属性与textvariable 不同,它是与这个控件本身绑定,
Checkbutton 自己有值:On 和Off 值,缺省状态On 为1,Off 为0。

设置Checkbutton的状态值

将一字符串与Checkbutton 的值绑定,每次点击Checkbutton,将打印出当前的值

from Tkinter import *
root = Tk()
v = StringVar()
def callCheckbutton():
      print v.get()
Checkbutton(root,variable = v,text = 'checkbutton value',onvalue = 'python', offvalue = 'tkinter', command= callCheckbutton).pack()
root.mainloop()

onvalue:指定选中状态时的值
offvalue:指定未选中状态的值

Checkbutton 的值不一定是1 或0,甚至不必是整形数值。可以通过onvalue 和offvalue 属
性设置Checkbutton 的状态值,代码中将On 设置为'python',Off 值设置为'Tkinter',程序的打
印值将不再是0 或1,而是'Tkinter’或‘python’'''

原创粉丝点击