tkinter中的單選框Radiobutton應用實例

原文地址

分類目錄——tkinter

  • 先看效果

    1584084703536

  • Radiobutton使用

    var1 = tk.StringVar()
    var1.set('B')   # 設置哪一個被默認選中,如果設置值不在可選項中,則全不被選中
    r1 = tk.Radiobutton(window, text='Option A',variable=var1, value='A',
                        command=print_selection)
    # Radiobutton   單選框
    # 可供傳入的屬性有: activebackground, activeforeground, anchor,
    # background, bd, bg, bitmap, borderwidth, command, cursor,
    # disabledforeground, fg, font, foreground, height,
    # highlightbackground, highlightcolor, highlightthickness, image,
    # indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
    # state, takefocus, text, textvariable, underline, value, variable,
    # width, wraplength.
    r1.pack(anchor='w')
    tk.Radiobutton(window, text='Option B',variable=var1, value='B', command=print_selection).pack()
    

    其中一個Radiobutton是一個選項,如果想要有多個可供選擇的選項就需要多寫幾個Radiobutton,注意同一組的需要互斥選中的需要設置variable屬性爲同一個

  • 用for循環迭代生成

    # 用for語句循環生成
    var2 = tk.StringVar()
    vlist = ['張','王','李','趙']
    for v in vlist:
        tk.Radiobutton(window, text='Option '+v,variable=var2, value=v).pack()
    
  • 最上面的Label

    # 根據選擇設置Label中顯示的值
    def print_selection():
        l.config(text='you have selected ' + var1.get())
        # 獲得var1的值,並配置給(config)Label中的text屬性(也就是在label中的顯示內容)
    
    l = tk.Label(window, bg='yellow', width=20, text='empty')
    l.pack()
    
  • 全部代碼

  • 參考文獻

    代碼主要來自 Radiobutton 選擇按鈕,略有改動

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