簡體   English   中英

如何將單選按鈕值附加到列表

[英]how to append radiobutton value to list

我正在制作OMR卡程序。 但是我有問題 我無法將單選按鈕的值附加到列表中。 我想創建用戶的答案列表並與真實答案進行比較,但是我無法創建用戶的答案列表。 我認為檢查功能是問題。 請幫我

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()

經過深思熟慮,這是我的最終解決方案。 我使用了Python內置的enumerate函數來遍歷問題,同時還使用計數來更有效和動態地創建新的Radiobuttons。 這樣,我們將選擇的答案添加到列表中,並且我們仍然可以使用您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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM