zoukankan      html  css  js  c++  java
  • Checkbutton

    #tkinter之Checkbutton篇

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

    1、一个简单的Checkbutton例子

    1 #创建一个Checkbutton,显示文本为'python'
    2 from tkinter import *
    3 
    4 root = Tk()
    5 Checkbutton(root,text='python').pack()
    6 root.mainloop()

    2、设置Checkbutton的回调函数

    1 from tkinter import *
    2 
    3 def callCheckbutton():
    4     print('you check this button')
    5 
    6 root = Tk()
    7 Checkbutton(root,text='chech python',command=callCheckbutton).pack()
    8 root.mainloop()
    9 #不管Checkbutton的状态如何,此回调函数都会被调用,即对话框你选或者不选,只要有点击,就会调用函数

    3、通过回调函数改变Checkbutton的显示文本text的值

     1 from tkinter import *
     2 
     3 def callCheckbutton():
     4     #改变v的值,即改变Checkbutton的显示值
     5     v.set('Check Tkinter')
     6 
     7 root = Tk()
     8 v = StringVar()#声明v是tkinter里面的一个字符串变量
     9 v.set('good good')#设定字符串变量v的值
    10 #绑定v到Checkbutton的属性textvariable
    11 Checkbutton(root,textvariable =v,command=callCheckbutton).pack()
    12 root.mainloop()

    4、上述的textvariable使用方法与Button的用法完全相同,使用此例是为了区别Checkbutton的另外一个属性variable,此属性与textvariable不同,

    它是与这个控件本身绑定,checkbutton本身有值,On与Off分别为1和0,

    也就是说,variable的值是Checkbutton本身的值,是0或1等其他类型的数值

    textvariable是里面显示的文本的值

     1 #显示Checkbutton的值
     2 from tkinter import *
     3 root =Tk()
     4 #将一整数与Checkbutton的值绑定,每次点击Checkbutton,将打印当前的值
     5 v = IntVar()#声明v是tkinter里面的一个整形变量
     6 
     7 Checkbutton(root,variable = v,text ='checkbutton value').pack()
     8 Label(root,textvariable = v).pack()
     9 
    10 root.mainloop()

    5、Checkbutton的值不仅仅是1或者0,可以是其他类型的数值,可以通过onvalue,offvalue属性设置状态值

    如下代码将On设置为python,Off设置为tkinter,程序打印值将不再是0或者1,而是tkinter和python

    1 from tkinter import *
    2 root = Tk()
    3 #将一字符串与Checkbutton的值绑定,每次点击Checkbutton将打印出当前的值
    4 v = StringVar()#声明v是tkinter里面的字符串变量
    5 def callCheckbutton():
    6     print(v.get())
    7 
    8 Checkbutton(root,variable = v,text = 'checkbutton value',onvalue = 'python',offvalue='tkinter',command=callCheckbutton).pack()
    9 root.mainloop()
  • 相关阅读:
    兼容python3 小烦
    fstring 和 海象赋值
    Go-gRPC的简单使用
    GO-操作etcd简单示例
    进度报告
    进度报告
    windown 10 安装redis
    在.Net Core中使用T4工具生成实体文件
    python-with关键字,json,pickie序列化与反序列化
    python-文件操作-读,写,追加
  • 原文地址:https://www.cnblogs.com/themost/p/6760567.html
Copyright © 2011-2022 走看看