如何将radiobutton值附加到列表中

时间:2018-06-12 16:37:23

标签: python tkinter python-requests

我制作了一张OMR卡计划。 但我有一个问题。 我不能将radiobutton的值附加到列表中。 我想制作用户的答案列表并与真实答案进行比较,但我无法制作用户的答案列表。 我觉得检查功能是个问题。 请帮帮我

from tkinter import *
from tkinter import ttk
from tkinter import messagebox
win = Tk()
win.title("Exam")
win.geometry('1530x300+0+690')

def problem1():
    for i in range(0,10):
        i += 1
        label = Label(win, text='%d.' % i)
        label.grid(column=0, row=i)
        radVar = IntVar()
        r1 = ttk.Radiobutton(win, text="num1", variable=radVar, value=1, command = check)
        r1.grid(column=1, row=i)
        r2 = ttk.Radiobutton(win, text="num2", variable=radVar, value=2, command = check)
        r2.grid(column=2, row=i)
        r3 = ttk.Radiobutton(win, text="num3", variable=radVar, value=3, command = check)
        r3.grid(column=3, row=i)
        r4 = ttk.Radiobutton(win, text="num4", variable=radVar, value=4, command = check)
        r4.grid(column=4, row=i)

def check():
    if radVar.get() == 1 :
        list.append(1)
    elif radVar.get() == 2 :
        list.append(2)
    elif radVar.get() == 3 :
        list.append(3)
    elif radVar.get() == 4 :
        list.append(4)

radVar = IntVar()
list=[]
problem1()
action = ttk.Button(win, text = "check the answer",command = check)
action.grid(column=0, row=11)

win.mainloop()

1 个答案:

答案 0 :(得分:0)

经过深思熟虑后,这是我的最终解决方案。我已经使用 Python 内置enumerate函数来循环遍历问题,同时还使用计数来更有效地动态创建新的Radiobutton。这样,我们会在列表选中时附加答案,我们仍然可以使用您的check the answer按钮查看所有提交的答案。

from tkinter import *
from tkinter import ttk

def problem1():
    for i in range(1,5):
        label = Label(win, text='%d.' % i)
        label.grid(column=0, row=i)
    for count, question in enumerate(questions, 1):
        radVar = IntVar()
        for i in range(1,5):
            button = ttk.Radiobutton(win, text="num%d" % i, variable=radVar, value=i, command=check)
            button.grid(row=count, column=i)
        answers.append(radVar)

def check():
    # check submitted answers against correct answers here
    for x in answers:
        print(x.get())

win = Tk()
win.title("Exam")
win.geometry('1530x300+0+690')
questions = ["num1", "num2", "num3", "num4"]
answers = []
problem1()
action = ttk.Button(win, text="check the answer", command = check)
action.grid(column=0, row=5)
win.mainloop()