Python tkinter编程之Checkbutton篇

本文详细介绍了Tkinter中Checkbutton的各种用法,包括基本使用、事件处理、文本修改、变量绑定及状态值设定,适合Tkinter初学者及进阶用户。
部署运行你感兴趣的模型镜像

1.Checkbutton第一个例子

# -*-coding:utf-8 -*-
'''
第一个checkButton例子
text:设置显示的文本
'''
from tkinter import *
root = Tk()
Checkbutton(root, text = 'python').pack()
root.mainloop()

运行效果图:

2.设置CheckButton的事件处理函数

#-*-coding:utf-8-*-
'''
设置CheckButton的事件处理函数
command:指定事件处理函数
'''
from tkinter import *
def callCheckbutton():
    print('you check this button')
root = Tk()
Checkbutton(root, text = 'check python', command = callCheckbutton).pack()
root.mainloop()

运行效果图:点击就会打印:you check this button

3.改变Checkbutton的显示文本

#-*-coding:utf-8-*-
'''
改变Checkbutton的显示文本
text:显示的文本内容
command:指定的事件处理函数
'''
from tkinter import *
def callCheckbutton():
    #改变v的值,即改变Checkbutton的显示值
    v.set('check tkinter')
root = Tk()
v = StringVar()
v.set('check python')
#绑定v到Checkbutton的属性textvariable
Checkbutton(root, text = 'check python', textvariable = v, command = callCheckbutton).pack()
root.mainloop()

运行效果图:

选中之后文字会变

4.将变量与Checkbutton绑定

#-*-coding:utf-8-*-
'''
将变量与Checkbutton绑定
variable:指定与Checkbutton绑定的变量
Checkbutton自己有值:On和Off值,缺省状态On为1, Off为0
'''
#显示Checkbutton的值
from tkinter import *
root = Tk()
#将一整数与Checkbutton的值绑定,每次点击Checkbutton,将打印出当前的值
v = IntVar()
def callCheckbutton():
    print(v.get())
Checkbutton(root, variable = v, text = 'checkbutton value', command = callCheckbutton).pack()
root.mainloop()

运行效果图:选中输出1,取消选中输出0

5.设置Checkbutton的状态值

# -*-coding:utf-8-*-
'''
设置Checkbutton的状态值
onvalue:指定选中状态时的值
offvalue:指定未选中状态的值
'''
from tkinter import *
root = Tk()
#将一字符串与Checkbutton的值绑定,每次点击Checkbutton,将打印出当前的值
v = StringVar()
def callCheckbutton():
    print(v.get())
#通过设置onvalue和offvalue可以设置Checkbutton的状态值,可以不为整形数值
Checkbutton(root, variable = v, text = 'checkbutton value', onvalue = 'python', offvalue = 'tkinter',
            command = callCheckbutton).pack()
root.mainloop()

运行效果:选中输出python, 取消选中输出 tkinter

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值