import tkinter as tk
window = tk.Tk()
window.title('checkbutton')
window.geometry('300x300')
label = tk.Label(window, bg='yellow', width=25, text = '')
label.pack()
checkbutton_1_variable = tk.BooleanVar()
checkbutton_2_variable = tk.BooleanVar()
def print_selected():
if(checkbutton_1_variable.get() and checkbutton_2_variable.get()):
label.config(text='I love both')
elif( checkbutton_1_variable.get() and (not checkbutton_2_variable.get())):
label.config(text='I do not love python')
elif( (not checkbutton_1_variable.get()) and checkbutton_2_variable.get()):
label.config(text='I do not love c++')
else:
label.config(text='I do not love either')
return
# onvalue=1, offvalue=0
# 选中的时候值为1,不选中的时候值为0
checkbutton_1 = tk.Checkbutton(window, text='python', variable=checkbutton_1_variable, onvalue=True, offvalue=False, command=print_selected)
checkbutton_2 = tk.Checkbutton(window, text='c++', variable=checkbutton_2_variable, onvalue=True, offvalue=False, command=print_selected)
checkbutton_1.pack()
checkbutton_2.pack()
window.mainloop()
效果: