Tkinter教程之Checkbutton 勾选项

51changxuePython评论1,229 views阅读模式

Tkinter教程之Checkbutton 勾选项

# Checkbutton又称为多选按钮,可以表示两种状态:On和Off,可以设置回调函数,每当点击此按钮时回调函数被调用
'''''1.一个简单的Checkbutton例子'''
# 创建一个Checkbutton,显示文本为"python"
from tkinter import *

root = Tk()
Checkbutton(root, text='python').pack()

'''''2.设置Checkbutton的回调函数'''


# 不管Checkbutton的状态如何,此回调函数都会被调用
def callCheckbutton1():
    print('you check this button')


Checkbutton(root, text='check python', command=callCheckbutton1).pack()


def callCheckbutton2():
    # 改变v的值,即改变Checkbutton的显示值
    v.set('check Tkinter')


'''''3.通过回调函数改变Checkbutton的显示文本text的值'''
v = StringVar()
v.set('check python3.5')
# 绑定v到Checkbutton的属性textvariable
Checkbutton(root, text='check python', textvariable=v, command=callCheckbutton2).pack()

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

# 将一整数与Checkbutton的值绑定,每次点击Checkbutton,将打印出当前的值
v2 = IntVar()


def callCheckbutton3():
    print(v2.get())


Checkbutton(root,
            variable=v2,
            text='checkbutton value',
            command=callCheckbutton3).pack()


'''''5.Checkbutton的值不仅仅是1或0,可以是其他类型的数值,可以通过onvalue和offvalue属性设置Checkbutton的状态值,
如下代码将On设置为
'python', Off值设置为
'Tkinter',程序的打印值将不再是0或1,而是
'Tkinter’或‘python’'''

# 将一字符串与Checkbutton的值绑定,每次点击Checkbutton,将打印出当前的值
v = StringVar()


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


Checkbutton(root,
            variable=v,
            text='checkbutton value',
            onvalue='python on',  # 设置On的值
            offvalue='tkinter off',  # 设置Off的值
            command=callCheckbutton).pack()
v.set('tkinter off')
root.mainloop()

# 6.还有其他的属性fg/bg/relief/width/height/justify/state使用方法与Button相同,不再举例。

运行结果:

Tkinter教程之Checkbutton 勾选项

继续阅读
51changxue
  • 本文由 发表于 2018年4月7日 20:08:27
  • 转载请务必保留本文链接:https://51changxue.com/443.html
pycharm永久破解激活教程 Python

pycharm永久破解激活教程

PyCharm是一种Python IDE,带有一整套可以帮助用户在使用Python语言开发时提高其效率的工具,比如调试、语法高亮、Project管理、代码跳转、智能提示、自动完成、...
Tkinter控件快速引用总结 Python

Tkinter控件快速引用总结

  文件名称: Tkinter控件快速引用总结代码.rar 文件大小: 4k 更新日期: 2018-7-29 文件版本: V1.0 免责声明: 本站大部分下载资源收集于网络,只做学习和交流使...
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定