zoukankan      html  css  js  c++  java
  • tkinter中checkbutton多选框控件和variable用法(六)

    checkbutton控件

    简单的实现多选:

     1 import tkinter
     2 
     3 wuya = tkinter.Tk()
     4 wuya.title("wuya")
     5 wuya.geometry("300x200+10+20")
     6 
     7 # 创建四个多选框
     8 cb1 = tkinter.Checkbutton(wuya,text='周杰伦')
     9 cb1.pack()
    10 cb2 = tkinter.Checkbutton(wuya,text='周星驰')
    11 cb2.pack()
    12 cb3 = tkinter.Checkbutton(wuya,text='爱舞涯')
    13 cb3.pack()
    14 cb4 = tkinter.Checkbutton(wuya,text='蔡依林')
    15 cb4.pack()
    16 
    17 wuya.mainloop()

    tkinter中如果不设置对齐方式,默认是居中的,如果要设置可以在pack()中加参数:cb1.pack(side='left')

    结果为:

    结合之前学的加lable和打印功能:

     1 import tkinter
     2 
     3 wuya = tkinter.Tk()
     4 wuya.title("wuya")
     5 wuya.geometry("300x200+10+20")
     6 
     7 # 加标签
     8 lb = tkinter.Label(wuya,text='请选择自己喜欢的名星(多选):',fg='blue')
     9 lb.pack()
    10 
    11 
    12 
    13 # 定义执行选择框后的函数
    14 def func():
    15     msg = ''
    16     if h1.get() == True: # 因为h1创建时是bool的运算,选中为真,不选为假
    17         msg += "周杰伦
    "
    18     if h2.get() == True:
    19         msg += "周星驰
    "
    20     if h3.get() == True:
    21         msg += "爱舞涯
    "
    22     if h4.get() == True:
    23         msg += "蔡依林
    "
    24 
    25     text.delete(0.0,tkinter.END)   # 清除text中的内容,0.0表示从第一行第一个字开始清除,end表示清除到最后结束
    26     text.insert('insert',msg)
    27 
    28 # 创建四个多选框
    29 h1 = tkinter.BooleanVar() # 设置选择框对象
    30 cb1 = tkinter.Checkbutton(wuya,text='周杰伦',variable=h1,command=func)
    31 cb1.pack()
    32 
    33 h2 = tkinter.BooleanVar()
    34 cb2 = tkinter.Checkbutton(wuya,text='周星驰',variable=h2,command=func)
    35 cb2.pack()
    36 
    37 h3 = tkinter.BooleanVar()
    38 cb3 = tkinter.Checkbutton(wuya,text='爱舞涯',variable=h3,command=func)
    39 cb3.pack()
    40 
    41 h4 = tkinter.BooleanVar()
    42 cb4 = tkinter.Checkbutton(wuya,text='蔡依林',variable=h4,command=func)
    43 cb4.pack()
    44 # side='left'表示左对齐
    45 
    46 # 创建一个文本框
    47 text = tkinter.Text(wuya,width=30,height=10)
    48 text.pack()
    49 
    50 
    51 wuya.mainloop()

    结果为:

     

    variable用法

    variable主要用于传参和绑定变量。主要参数有:variabletextvariableonvalueoffvaluevalue

    他是双向绑定的,也就是说如果该变量发生变化,随之绑定的控件也会变化,与他保持一致

    常用的variable变量有:

      x = StringVar()  保存一个 string 类型变量, 默认值为""

      x = IntVar()  保存一个整型变量, 默认值为0

      x = DoubleVar()  保存一个浮点型变量,默认值为0.0

      x = BooleanVar()  保存一个布尔型变量,返回值为0表示假,1表示真

    对他的操作主要有两个:

      设置他的值,用set()方法,即:x.set()

      得到他的值,用get()方法,即:x.get()

  • 相关阅读:
    第七十天 how can I 坚持
    第六十九天 how can I 坚持
    第六十八天 how can I 坚持
    第六十七天 how can I 坚持 (补昨天)
    第六十六天 how can I 坚持··
    第六十五天 how can I 坚持
    第六十四天 how can i 坚持
    第六十三天 how can I 坚持
    MyEclipse10 中的两种FreeMarker插件的安装与配置
    画板社交工具开发分享——HTML5 canvas控件、PHP、社交分享学习(四)
  • 原文地址:https://www.cnblogs.com/tynam/p/8778667.html
Copyright © 2011-2022 走看看