如何获取数组中的值

How to get the values in array

我正在尝试 return 数组 vars 中的值,但我只得到了它。我是新手,所以有人可以解释一下这些值是什么以及为什么它们不是 return 1 或 0 作为复选按钮的状态吗?

[<tkinter.IntVar object at 0x0318BCD0>, <tkinter.IntVar object at 0x0318BD70>, <tkinter.IntVar 
object at 0x0318BDD0>, <tkinter.IntVar object at 0x0318BE30>, <tkinter.IntVar object at 0x0318BE90>, <tkinter.IntVar object at 0x0318BF10>, <tkinter.IntVar object at 0x0318BF70>, <tkinter.IntVar object at 0x0318BFD0>, <tkinter.IntVar object at 0x03196050>, <tkinter.IntVar object at 0x03196070>, <tkinter.IntVar object at 0x031960D0>, <tkinter.IntVar object at 0x03196110>, <tkinter.IntVar object at 0x03196150>, <tkinter.IntVar object at 0x03196190>, <tkinter.IntVar object 
at 0x031961D0>, <tkinter.IntVar object at 0x03196210>, <tkinter.IntVar object at 0x03196250>, <tkinter.IntVar object at 0x03196290>, <tkinter.IntVar object at 0x031962D0>, <tkinter.IntVar object at 0x03196310>, <tkinter.IntVar object at 0x03196350>, <tkinter.IntVar object at 0x03196390>, <tkinter.IntVar object at 0x031963D0>, <tkinter.IntVar object at 0x03196410>, <tkinter.IntVar object at 0x03196450>, <tkinter.IntVar object at 0x03196490>, <tkinter.IntVar object at 0x031964D0>, <tkinter.IntVar object at 0x03196510>, <tkinter.IntVar object at 0x03196550>, <tkinter.IntVar object at 0x03196590>, <tkinter.IntVar object at 0x031965D0>, <tkinter.IntVar object at 0x03196610>, <tkinter.IntVar object at 0x03196650>, <tkinter.IntVar object at 0x03196690>, <tkinter.IntVar object at 0x031966D0>, <tkinter.IntVar object at 0x03196710>, <tkinter.IntVar object at 0x03196750>, <tkinter.IntVar object at 0x03196790>, <tkinter.IntVar object at 0x031967D0>, <tkinter.IntVar object at 0x03196810>, <tkinter.IntVar object at 0x03196850>, <tkinter.IntVar object at 0x03196890>, <tkinter.IntVar object at 0x031968D0>, <tkinter.IntVar object at 0x03196910>, <tkinter.IntVar object at 0x03196950>, <tkinter.IntVar object at 0x03196990>, <tkinter.IntVar object at 0x031969D0>, <tkinter.IntVar object at 0x03196A10>, <tkinter.IntVar object at 0x03196A50>, <tkinter.IntVar object at 0x03196A90>]

这是我使用的来自 post

的代码
import tkinter as tk

root = tk.Tk()

scrollbar = tk.Scrollbar(root)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

checklist = tk.Text(root, width=20)
checklist.pack()

vars = []
for i in range(50):
    var = tk.IntVar()
    vars.append(var)
    checkbutton = tk.Checkbutton(checklist, text=i, variable=var)
    checklist.window_create("end", window=checkbutton)
    checklist.insert("end", "\n")

checklist.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=checklist.yview)

# disable the widget so users can't insert text into it
checklist.configure(state="disabled")

root.mainloop()

要从 tk.IntVar() 中获取值,您需要使用 .get() 方法。因此,如果您想获得一个值列表,您需要在 vars 数组的每个元素上使用 .get()

vars 是已保存的关键字,因此您应该使用它,您可以使用名称 tk_vars 代替。

values = []

for var in tk_vars:
   values.append(var.get())

print(values)

如果您想使用列表理解:

values = [var.get() for var in tk_vars]

您没有在 var 上使用 .get() 方法。详细了解这些方法 here