我不到3周前才开始编写代码(在Lynda中上了课),现在正在使用GUI进行操作,使用户可以对列表进行打勾/取消打勾。我设法做到了,但解决方法效率低下(有人给了我一个建议)。

我所做的基本上是为每个复选框调用一个变量,并将复选框状态插入其中。因此,如果列表中有100个复选框,则需要创建100个变量。以下是我编写的工作代码。

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

var1t1 = tk.IntVar()
var2t1 = tk.IntVar()
var3t1 = tk.IntVar()

var_name = []
root.title("Testing Checkbox")
root.geometry("200x150")

def boxstates_t1():
    var_name = [var1t1.get(), var2t1.get(), var3t1.get()]
    print(var_name)

# -----------------Checkbox-----------------
labelName = tk.Label(root, text = "Name")
labelName.pack(anchor = tk.W)

check1_t1 = ttk.Checkbutton(root, text = "Mike", variable = var1t1)
check1_t1.pack(anchor = tk.W)

check2_t1 = ttk.Checkbutton(root, text = "Harry", variable = var2t1)
check2_t1.pack(anchor = tk.W)

check3_t1 = ttk.Checkbutton(root, text = "Siti", variable = var3t1)
check3_t1.pack(anchor = tk.W)

# -----------------Button-----------------

btn2 = ttk.Button(root, text="Show", command = boxstates_t1)
btn2.pack(side=tk.RIGHT)

root.mainloop()


然后我四处搜寻,发现很少有代码使我使用for循环来打印列表。我初始化var_name = [],以便它将捕获列表中的每个复选框状态。

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
var1 = tk.IntVar()

var_name = []
root.title("Testing Checkbox")
root.geometry("200x150")

def boxstates():
    var_name = var1.get()
    print(var_name)

# ------------------Chekbox-------------
name1 = ["Mike", "Harry", "Siti"]

labelName = tk.Label(root, text = "Name")
labelName.pack(anchor = tk.W)

for checkboxname in name1:
    check1_t1 = ttk.Checkbutton(root, text=checkboxname, variable=var1)
    check1_t1.pack(anchor = tk.W)
# ------------------Button-------------
btn2 = ttk.Button(root, text="Show", command = boxstates)
btn2.pack(side=tk.RIGHT)

root.mainloop()


但是我无法独立打勾该复选框,并且打印结果也像单个变量一样返回。我在错误地处理数组var_name = []吗?我目前迷路了,不知道下一步该去哪里。

任何建议都将不胜感激。

最佳答案

import tkinter as tk
from tkinter import ttk

def boxstates():
    finalValue = []
    for x in checkboxList:
        finalValue.append(x.get())
    print(finalValue)

root = tk.Tk()

root.title("Testing Checkbox")
root.geometry("200x150")

# ------------------Chekbox-------------

checkboxList = [tk.IntVar(), tk.IntVar(), tk.IntVar()] # if you want to add more you can either append to it or declare it before runtime
name1 = ["Mike", "Harry", "Siti"]

labelName = tk.Label(root, text = "Name")
labelName.pack(anchor = tk.W)

def createCheckboxes():
    for x, y in zip (checkboxList, name1):
        check1_t1 = ttk.Checkbutton(root, text=y, variable=x)
        check1_t1.pack(anchor = tk.W)

# ------------------Button-------------
btn2 = ttk.Button(root, text="Show", command = boxstates)
btn2.pack(side=tk.RIGHT)

createCheckboxes()
root.mainloop()

10-04 16:22
查看更多