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

Python Tkinter如何获取选中的Checkbutton项至列表?

解决Tkinter CheckButton选中项获取问题

你遇到的核心问题是遍历checks列表时的对象类型判断错误,以及没有正确访问自定义类里的状态变量。以下是修正方案:

修正后的select函数

def select():
    chosen = []
    for cb_instance in checks:
        if cb_instance.var.get() == 1:
            chosen.append(cb_instance.title)
    # 这里可以添加你的后续操作,比如打印或处理选中列表
    print("已选中的项:", chosen)

关键说明

  • 你自定义的CheckButton类每个实例都包含var(记录选中状态的IntVar)和title(按钮文本)属性
  • 遍历checks时,循环变量是CheckButton类的实例,不是索引,所以直接访问实例的属性即可
  • 通过var.get()获取选中状态:1代表选中,0代表未选中,和你初始化时设置的onvalue、offvalue对应

完整可运行代码

import tkinter
from tkinter import *

mylist = ['Alfa', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot', 'Golf', \
          'Hotel', 'India', 'Juliett', 'Kilo', 'Lima']

class CheckButton:
    def __init__(self, master, title):
        self.var = IntVar()
        self.var.set(0)
        self.title = title
        self.cb = Checkbutton(master, text=title, variable=self.var, onvalue=1, \
                              offvalue=0)
        self.cb.pack(side = TOP)

def select():
    chosen = []
    for cb_instance in checks:
        if cb_instance.var.get() == 1:
            chosen.append(cb_instance.title)
    print("已选中的项:", chosen)
    
#Window 
window = Tk()
f1 = Frame(window)
checks = []
for i in mylist:
    checks.append(CheckButton(window, i))
button = Button(window, text="Select!", command=select)
button.pack(side="bottom")
window.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 11:30:53