You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建一键全选Tkinter复选框的按钮?

Tkinter 实现复选框列表与全选功能

在你现有代码的基础上,只需添加一个全选函数和对应的按钮,就能实现一键选中所有复选框的功能。具体修改后的完整代码如下:

from tkinter import *


def on_click():
    lst = [interests[i] for i, chk in enumerate(chks) if chk.get()]
    print(",".join(lst))


def select_all():
    # 遍历所有复选框变量,设置为选中状态
    for var in chks:
        var.set(True)


interests = ['Music', 'Book', 'Movie', 'Photography', 'Game', 'Travel']
root = Tk()
root.option_add("*Font", "impact 30")
chks = [BooleanVar() for i in interests]

Label(root, text="Your interests", bg="gold").pack()
for i, s in enumerate(interests):
    Checkbutton(root, text=s, variable=chks[i]).pack(anchor=W)  # W = West

# 添加全选按钮
Button(root, text="全选", command=select_all).pack()
Button(root, text="submit", command=on_click).pack()

root.mainloop()

关键实现说明:

  • select_all 函数通过遍历所有存储复选框状态的 BooleanVar 对象,调用 set(True) 将每个复选框统一设为选中状态
  • 新增的“全选”按钮绑定了该函数,点击后即可完成一键全选操作

内容的提问来源于stack exchange,提问作者HOW TO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 06:36:32