【问题标题】:Is there a way to define a command for radio buttons to show right or false answer in multiple choice quiz?有没有办法为单选按钮定义一个命令,以在多项选择测验中显示正确或错误的答案?
【发布时间】:2019-02-13 00:38:26
【问题描述】:

我是一名初学者,尝试使用 Tkinter 在 python 中创建多项选择测验。对不起,如果我创建了一个混乱的代码。我正在使用单选按钮来获得不同的答案。我想在选择选项 1 时显示消息“这是正确答案”,在选择任何其他选项时显示“这是错误答案”。目前,无论选择何种选项,消息始终是“这是错误答案”。我明白价值与它无关,但我没有找到正确的方法。有没有办法定义这种命令?非常感谢您提供的任何帮助、建议和答案。

from tkinter import *
from tkinter import ttk
from tkinter import messagebox

window = Tk()
window.title("Quiz")
window.geometry("500x150")
score = 0
def inst():
    t = Label(window, text="Choose the correct statement to answer the 
question")
    t.pack()

def start():
    start_game()

greet = Label(window, text="Welcome to the Quiz")
greet.pack()
startButton = Button(window, command=start, text="Start")
startButton.pack()
instr = Button(window, text="Instructions", command=inst)
instr.pack()
end = Button(window, text="Exit", command=window.destroy)
end.pack()

def start_game():
    top = Toplevel()
    top.title("Question 1")
    var = StringVar()
    def check():
        if var.get() is True:
            messagebox.showinfo('Congrats', message='This is the correct 
answer.Score is {}'.format(score))
        else:
            messagebox.showinfo('Lose', message='This answer is wrong.')
    R1 = Radiobutton(top,
    text="Option 1",
    indicatoron=0,
    width=20,
    padx=20,
    pady=10,
    variable=var,
    value=True,
    command=check)
    R1.pack( anchor = W )
    R2 = Radiobutton(top,
    text="Option 2",
    indicatoron=0,
    width=20,
    padx=20,
    pady=10,
    variable=var,
    value=False,
    command=check)
    R2.pack( anchor = W )
    R3 = Radiobutton(top,
    text="Option 3",
    indicatoron=0,
    width=20,
    padx=20,
    pady=10,
    variable=var,
    value=False,
    command=check)
    R3.pack( anchor = W)
    label = Label(top)
    label.pack()

window.mainloop()

【问题讨论】:

    标签: python tkinter radio-button


    【解决方案1】:

    由于您使用的是布尔值,我认为改用 BooleanVar 更有意义。

    如果您知道哪个是正确的,您可以简单地将按钮传递给check 函数并更改它们的颜色:

    def check(btn1, btn2):
        btn1.config(bg='green')
        btn2.config(bg='red')
    

    然后像这样修改单选按钮(就在您定义它们的位置下方):

    for btn in (R1, R2):
        btn.config(command=lambda btn1=R1,btn2=R2:check(btn1,btn2))
    

    注意,我使用了两个按钮,因为 R2R3 具有相同的值,因此它们可以有效地组合为一个。

    这是一个例子;它使用一个按钮列表来存储所有已创建的单选按钮,并根据其文本更改每个单选按钮的颜色,同时检查玩家是否得到正确的答案。

    import tkinter as tk
    
    def check_answer():
        if question_answer.get() == 2: #get the value of the integer variable
            print('you got it right')  #if it has been set to 2 by the player, they got it right
        for btn in btnlist: #check each of our radiobuttons
            if int(btn['text']) == 2: #if the text of that button is equal to the correct answer
                btn.config(bg='green') #make it green
            else:
                btn.config(bg='red') #otherwise make it red
    
    win = tk.Tk()
    question = 'What is 1+1?' #put your question here
    
    question_answer = tk.IntVar() #we use an Integer Variable to store the value of the answer
    question_answer.set(0) #we set the value of the correct answer to 0
    
    lbl = tk.Label(win, text=question)
    lbl.grid(columnspan=4)
    
    column = 0
    btnlist = []
    for answer in range(4): #create radiobuttons in a for loop
        btn = tk.Radiobutton(win, text=str(answer), variable=question_answer,
                             value=answer) #associate each button with the answer variable
        #but give each button its own unique value
        btnlist.append(btn)
        btn.grid(row=1, column=column)
        column += 1
    
    confirm_btn = tk.Button(win, text='Confirm', command=check_answer)
    confirm_btn.grid(columnspan=4)
    win.mainloop()
    

    在此示例中,我使用了IntVar,因为答案是整数,您也可以根据需要以相同的方式使用BooleanVarStringVar

    编辑:根据您在 cmets 中的要求:

    import tkinter as tk
    
    win = tk.Tk()
    text_to_add_to_btns = ['A', 'B', 'C', 'D', 'E'] #change to whatever text you like
    #with however many elements which represent each individual button
    btn_list = []
    Column = 0
    for txt in text_to_add_to_btns:
        btn = tk.Button(win, text=txt)
        btn.grid(row=0, column=Column, sticky='nesw')
        btn_list.append(btn)
        Column += 1
    win.mainloop()
    

    我们创建一个默认列表,其中包含要作为单独列表元素添加到每个按钮的文本。然后我们遍历该列表为每个元素创建每个按钮,并将按钮的文本设置为该元素,然后将其附加到我们单独的按钮列表中。

    【讨论】:

    • 非常感谢您的回答,非常有帮助。你能给我关于如何将文本分配给不同按钮的建议吗?我似乎不知道如何将它们保留在列表中,但同时给它们不同的文本。
    • 您可以创建一个列表,其中包含您要添加到按钮的所有文本,然后遍历该列表 - 就像我所做的 for answer in range(4) 一样,但您可以使用您的 range(4) 而不是放置在按钮上的文本列表。
    • 非常感谢您的快速回复。很抱歉问了这么多问题,但我对此还是很陌生。很抱歉问了这么多问题,但我对一切都很陌生。那么我应该添加一个带有文本的附加列表,然后在另一个列表中使用它而不是 range(4) 还是保留一个列表并更改 btnlist 并在其中包含文本?因为我这样做的方式我失去了颜色变化或文本没有应用于按钮。
    • @Lana 查看更新的答案,希望对您有所帮助。如果您希望整数出现在您的按钮上,您可以使用range(number_of_buttons_here),如果您想要字符串,请使用编辑中描述的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 2022-11-13
    • 2018-11-30
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    相关资源
    最近更新 更多