效果如下图:
# 全选 反选
import tkinter as tk
from tkinter import ttk,messagebox,filedialog
#点击勾选框触发
def getselect(item):
print(item,'selected')
#反选
def unselectall():
for index,item in enumerate(list1):
v[index].set('')
#全选
def selectall():
for index,item in enumerate(list1):
v[index].set(item)
#获取选择项
def showselect():
selected=[i.get() for i in v if i.get()]
print(selected)
window=tk.Tk()
window.geometry('500x500')
frame1=tk.Frame(window,pady=10,padx=15)
frame1.grid(row=0,column=0)
#全选反选
opt=tk.IntVar()
ttk.Radiobutton(frame1,text='全选',variable=opt,value=1,command=selectall).grid(row=0,column=0,sticky='w')
ttk.Radiobutton(frame1,text='反选',variable=opt,value=0,command=unselectall).grid(row=0,column=1,sticky='w')
list1=['阿尔及利亚', '澳大利亚', '博茨瓦纳', '巴西', '文莱', '加拿大', '智利', '中国', '哥伦比亚', '捷克', '丹麦', '美国', '印度']
v=[]
#设置勾选框,每四个换行
for index,item in enumerate(list1):
v.append(tk.StringVar())
ttk.Checkbutton(frame1,text=item,variable=v[-1],onvalue=item,offvalue='',command=lambda item=item:getselect(item)).grid(row=index//4+1,column=index%4,sticky='w')
ttk.Button(frame1,text="获取选择的国家",command=showselect).grid(row=index//4+2,column=0)
window.mainloop()