效果:
選擇不同的復選框,會顯示選中的內容在頂部label上
import tkinter as tk # 定義窗口 window = tk.Tk() window.title('my window') # 窗口title window.geometry('350x300') # 窗口尺寸 # 定義Label l = tk.Label(window, bg="yellow", width=20, text='you have selected None') l.pack() def print_selection(): if (var1.get() == 1 and var2.get() == 0): l.config(text='I love only Python') elif (var1.get() == 0 and var2.get() == 1): l.config(text='I love only C++') elif (var1.get() == 1 and var2.get() == 1): l.config(text='I love both') else: l.config(text='I do not love either') var1 = tk.IntVar() var2 = tk.IntVar() ''' state狀態:active, disabled,normal onvalue:復選按鈕選中時變量的值 offvalue:復選按鈕未選中時變量的值 variable:通過變量的值確定哪些復選按鈕被選中,每個復選按鈕使用不同的變量,復選按鈕之間相互獨立 ''' c1 = tk.Checkbutton(window, text='Python', variable=var1, onvalue=1, offvalue=0, command=print_selection) c2 = tk.Checkbutton(window, text='C++', variable=var2, onvalue=1, offvalue=0, command=print_selection) c1.pack() c2.pack() window.mainloop()
總結:
1.復選框被勾選上時,variable = var1 = onvalue =1
復選框沒有被勾上時,variable = var1 = offvalue =0
2.獲取值使用var1.get()
3.條件判斷語句,python2和python3中略有不同,python3中使用and or not
4.使用state參數可以表明復選框的狀態,參數有active,disabled,normal