分享

Tkinter教程之Checkbutton篇

 Mq_Guo 2017-07-23
[python] view plain copy
  1. # Tkinter教程之Checkbutton篇  
  2. # Checkbutton又称为多选按钮,可以表示两种状态:On和Off,可以设置回调函数,每当点击此按钮时回调函数被调用  
  3. '''''1.一个简单的Checkbutton例子'''  
  4. # 创建一个Checkbutton,显示文本为"python"  
  5. from tkinter import *  
  6.   
  7. root = Tk()  
  8. Checkbutton(root, text='python').pack()  
  9.   
  10. '''''2.设置Checkbutton的回调函数'''  
  11.   
  12.   
  13. # 不管Checkbutton的状态如何,此回调函数都会被调用  
  14. def callCheckbutton1():  
  15.     print('you check this button')  
  16.   
  17.   
  18. Checkbutton(root, text='check python', command=callCheckbutton1).pack()  
  19.   
  20.   
  21. def callCheckbutton2():  
  22.     # 改变v的值,即改变Checkbutton的显示值  
  23.     v.set('check Tkinter')  
  24.   
  25.   
  26. '''''3.通过回调函数改变Checkbutton的显示文本text的值'''  
  27. v = StringVar()  
  28. v.set('check python3.5')  
  29. # 绑定v到Checkbutton的属性textvariable  
  30. Checkbutton(root, text='check python', textvariable=v, command=callCheckbutton2).pack()  
  31.   
  32. '''''4.上述的textvariable使用方法与Button的用法完全相同,使用此例是为了区别Checkbutton的另外的一个属性variable, 
  33. 此属性与textvariable不同,它是与这个控件本身绑定,Checkbutton自己有值:On和Off值,缺省状态On为1,Off为0,如:'''  
  34.   
  35. # 将一整数与Checkbutton的值绑定,每次点击Checkbutton,将打印出当前的值  
  36. v2 = IntVar()  
  37.   
  38.   
  39. def callCheckbutton3():  
  40.     print(v2.get())  
  41.   
  42.   
  43. Checkbutton(root,  
  44.             variable=v2,  
  45.             text='checkbutton value',  
  46.             command=callCheckbutton3).pack()  
  47. root.mainloop()  

[python] view plain copy
  1. '''''5.Checkbutton的值不仅仅是1或0,可以是其他类型的数值,可以通过onvalue和offvalue属性设置Checkbutton的状态值, 
  2. 如下代码将On设置为'python',Off值设置为'Tkinter',程序的打印值将不再是0或1,而是'Tkinter’或‘python’'''  
  3. from tkinter import *  
  4.   
  5. root = Tk()  
  6. # 将一字符串与Checkbutton的值绑定,每次点击Checkbutton,将打印出当前的值  
  7. v = StringVar()  
  8.   
  9.   
  10. def callCheckbutton():  
  11.     print(v.get())  
  12.   
  13.   
  14. Checkbutton(root,  
  15.             variable=v,  
  16.             text='checkbutton value',  
  17.             onvalue='python on',  # 设置On的值  
  18.             offvalue='tkinter off',  # 设置Off的值  
  19.             command=callCheckbutton).pack()  
  20. v.set('tkinter off')  
  21. root.mainloop()  
  22.   
  23. # 6.还有其他的属性fg/bg/relief/width/height/justify/state使用方法与Button相同,不再举例。  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多