Python打印复选框值

时间:2020-01-20 19:58:09

标签: python tkinter

我正在尝试打印所选复选框的值。有人可以帮我指出正确的方向吗?我在这条线上出现错误-print(my_items [item])

这是错误:

TypeError:列表索引必须是整数或切片,而不是IntVar

import tkinter as tk
from tkinter import *

top = tk.Tk()
top.wm_title("Checklist")
my_items = ['pizza','breadsticks','wings','CocaCola','brownie'] 
check_boxes = {item:IntVar() for item in my_items}

def confirm():
    for item in check_boxes.values():
        if item.get() == 1:
            print(my_items[item])

for item in my_items:
    CB = Checkbutton(top, text = item, variable = check_boxes[item], anchor = W,  onvalue = 1, offvalue = 0, height=1, width = 50)
    CB.pack()

B1 = tk.Button(top, text = "confirm", command = confirm)
B1.pack()


top.mainloop()

1 个答案:

答案 0 :(得分:0)

如果您创建了类似的字典

[[1]]
[1] "SPG_L"           "subgenual_ACC_R"

[[2]]
[1] "SPG_R"      "MTG_L_pole"

[[3]]
[1] "MTG_L_pole"     "CerebellumGM_L"

[[4]]
[1] "SFG_pole_R"         "IFG_triangularis_L"

[[5]]
[1] "SFG_pole_R"        "IFG_opercularis_L"

那么您应该使用字典中的check_boxes = {'pizza': IntVar(), ...} keys

values中,您会收到所需的文本key

'pizza'

def confirm():
    for key, item in check_boxes.items():
        if item.get() == 1:
            print(key)

顺便说一句::您还可以使用import tkinter as tk # from tkinter import * # PEP8: `import *` is not preferred # --- functions --- def confirm(): for key, item in check_boxes.items(): if item.get() == 1: print(key) # --- main --- my_items = ['pizza', 'breadsticks', 'wings', 'CocaCola', 'brownie'] root = tk.Tk() check_boxes = {item:tk.IntVar() for item in my_items} for item in my_items: cb = tk.Checkbutton(root, text=item, variable=check_boxes[item], anchor='w', onvalue=1, offvalue=0, width=50) cb.pack() b1 = tk.Button(root, text="confirm", command=confirm) # PEP8: without spaces around `=`, `lower_case_names` for variables b1.pack() root.mainloop() StringVar()

onvalue='pizza'