tkinter多選框Checkbutton應用實例

原文地址

分類目錄——tkinter

  • 先看效果

    1584087774034

    其中上面是一個Label,用來根據選擇情況作出相應的展示;下面是一組複選框(Checkbutton)

  • Checkbutton使用實例

    var1 = tk.IntVar()
    var1.set(1)     # 如果設置值是onvalue的值,就默認選中;如果設置值是offvalue或者非on非off的值,就默認不選中
    var2 = tk.IntVar()
    c1 = tk.Checkbutton(window, text='Python', variable=var1, onvalue=1, offvalue=0, command=print_selection)
    # Checkbutton   複選框
    # 其中
    # variable  用來傳遞值的變量
    # onvalue   如果被選中var1的值就是onvalue的值
    # offvalue  如果未被選中var1的值就是offvalue的值
    # Valid resource names: activebackground, activeforeground, anchor,
    # background, bd, bg, bitmap, borderwidth, command, cursor,
    # disabledforeground, fg, font, foreground, height,
    # highlightbackground, highlightcolor, highlightthickness, image,
    # indicatoron, justify, offvalue, onvalue, padx, pady, relief,
    # selectcolor, selectimage, state, takefocus, text, textvariable,
    # underline, variable, width, wraplength.
    c2 = tk.Checkbutton(window, text='Java', variable=var2, onvalue=1, offvalue=0, command=print_selection)
    c1.pack()
    c2.pack()
    
  • 上面的Label

    # 根據複選框的選擇設定Label的值
    def print_selection():
        if (var1.get() == 1) & (var2.get() == 0):   #如果選中第一個選項,未選中第二個選項
            l.config(text='I love only Python ')
        elif (var1.get() == 0) & (var2.get() == 1): #如果選中第二個選項,未選中第一個選項
            l.config(text='I love only C++')
        elif (var1.get() == 0) & (var2.get() == 0):  #如果兩個選項都未選中
            l.config(text='I do not love either')
        else:
            l.config(text='I love both')             #如果兩個選項都選中
    # Label
    l = tk.Label(window, bg='yellow', width=20, text='empty')
    l.pack()
    
  • 全部代碼

  • 參考文獻

    代碼主要來自 Checkbutton 勾選項,略有改動

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章