欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

tkinter如何獲取復選框(Checkbutton)的值

 更新時間:2023年01月28日 09:37:03   作者:烏拉隊長  
這篇文章主要介紹了tkinter如何獲取復選框(Checkbutton)的值問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

tkinter獲取復選框(Checkbutton)的值

定義GUI:

from tkinter import *
 
# 初始化Tk()
myWindow = Tk()
# 設置標題
myWindow.title('Python GUI Learning')
myWindow.geometry("%dx%d+%d+%d"%(400, 200, 200, 200))
# 創(chuàng)建Checkbutton
checkVar = StringVar(value="0")
check = Checkbutton(myWindow, text="Checkbutton test", variable=checkVar)
check.grid(row=0, column=0, sticky=W, padx=2 ,pady=5)
# 定義按鈕點擊事件
def button_Click(event=None):
    print(checkVar.get())
 
# 創(chuàng)建兩個按鈕
b1 =Button(myWindow, text='click me' , relief='raised', width=8, height=1, command=button_Click)
b1.grid(row=0, column=2, sticky=W, padx=2 ,pady=10)
 
# 進入消息循環(huán)
myWindow.mainloop()

效果:

對復選框進行操作后,點擊按鈕輸出信息:

tkinter包的使用-Checkbutton

下面的例子講一下如何使用Checkbutton,它和Radiobutton的區(qū)別是,Radiobutton只可以選中一個,是單選按鈕,Checkbutton可以同時選中多個,是多選按鈕。

只選中Python:

只選中C++:

兩個都選中:

都不選:

代碼:

import tkinter as tk
 
window=tk.Tk()
window.title('my window')
window.geometry('200x100')
 
l=tk.Label(window,
           bg='yellow',
           width=20,
           text='empty')
l.pack()
 
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')
 
 
 
var1=tk.IntVar()
var2=tk.IntVar()
c1=tk.Checkbutton(window,
                  text='Python',
                  variable=var1,
                  onvalue=1,
                  offvalue=0,
                  command=print_selection
                  )
c1.pack()
c2=tk.Checkbutton(window,
                  text='C++',
                  variable=var2,
                  onvalue=1,
                  offvalue=0,
                  command=print_selection
                  )
c2.pack()
 
window.mainloop()

在Checkbutton()中參數(shù)onvalue和前面講的部件radiobutton中的value相似, 當我們選中了這個checkbutton,onvalue的值1就會放入到var1中, 然后var1將其賦值給參數(shù)variable,offvalue用法相似,但是offvalue是在沒有選中這個checkbutton時,offvalue的值1放入var1,然后賦值給參數(shù)variable 這是創(chuàng)建一個checkbutton部件,以此類推,可以創(chuàng)建多個checkbutton

在print_selection()中config在之前的例子中就是將參數(shù)text的值顯示,這里的var1.get() == 1 就是前面所說的var1獲得的變量onvalue=1,var1.get() == 0即是var1獲得的變量offvalu=0同理var2也是如此。

總結

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

最新評論