如何在Tkinter GUI中通过按钮将所有星级复选框设为选中状态
Tkinter星级复选框全选功能修改建议
你的代码里selectAllRating函数存在问题:所有复选框的onvalue是各自对应的星级(5星对应"5"、4星对应"4"……1星对应"1"),但你现在把所有StringVar都设为"1",这样只有1星复选框会被选中,其他星级不会生效。
修改方案如下:
- 遍历
starCheckBox时,根据每个变量对应的复选框星级,设置对应的onvalue值 - 补充创建触发
selectAllRating函数的按钮
修正后的完整代码:
from tkinter import * master = Tk() starCheckBox = [] for i in range(5): option = StringVar(value="") starCheckBox.append(option) Checkbutton(master, text='5 Stars',variable=starCheckBox[0], onvalue="5", offvalue="").place(x=0,y=20) Checkbutton(master, text='4 Stars',variable=starCheckBox[1], onvalue="4", offvalue="").place(x=100,y=20) Checkbutton(master, text='3 Stars',variable=starCheckBox[2], onvalue="3", offvalue="").place(x=200,y=20) Checkbutton(master, text='2 Stars',variable=starCheckBox[3], onvalue="2", offvalue="").place(x=300,y=20) Checkbutton(master, text='1 Stars',variable=starCheckBox[4], onvalue="1", offvalue="").place(x=400,y=20) Button(master, text='Select all Hotel(s)', command=selectAllHotel).place(x=0,y=190) # 添加全选星级的按钮 Button(master, text='Select all Ratings', command=selectAllRating).place(x=150,y=190) def selectAllRating(): # 遍历每个变量,对应设置各自的onvalue for idx, var in enumerate(starCheckBox): # 索引0对应5星,所以星级是5 - idx var.set(str(5 - idx)) # 假设selectAllHotel函数已定义 def selectAllHotel(): pass master.mainloop()
修改说明:
- 用
enumerate获取每个StringVar的索引,通过5 - idx计算出对应的星级值,设置给变量,这样每个复选框都会被选中 - 添加了触发
selectAllRating的按钮,确保功能可以被触发
内容的提问来源于stack exchange,提问作者诒通Yi Tong
相关产品推荐
相关产品推荐

