如何使用IntVar调用二维数组中的元素

时间:2018-02-12 20:51:28

标签: python tkinter

我正在尝试制作一个游戏,生成带有问题的框架,并将答案作为按钮放在它们下面。我差不多完成了基本代码,但我需要一种方法来比较玩家点击的答案和正确的答案。为此,我将正确的答案放在与所提问题相对应的元素的第一个元素中。即[[正确答案,错误,错误,错误],[正确,错误,错误,错误]]。

我无法使用IntVar调用正确的答案并访问正确的元素。

def check_answer(self, answer, page_name):
    global answers
    score = IntVar(self)
    correct = IntVar(self)
    if answer == answers[correct][0]:
        s = score.get() + 1
        score.set(s)
    print(score)
    frame = self.frames[page_name]
    frame.tkraise()
    correct = correct.get()+1
    correct.set(correct)

当我按下按钮时,我收到以下错误消息:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Chris\AppData\Local\Programs\Python\Python36-32\Lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
  File "C:/Users/Chris/Desktop/Paul's stuff/Paul/CpmpProject/gamescreenv3.py", line 62, in <lambda>
    answer = tkinter.Button(self, text=answers[0][i], command=lambda answer=i: controller.check_answer(answer, "QuestionTwo"))
  File "C:/Users/Chris/Desktop/Paul's stuff/Paul/CpmpProject/gamescreenv3.py", line 44, in check_answer
    if answer == answers[correct][0]:
TypeError: list indices must be integers or slices, not IntVar

1 个答案:

答案 0 :(得分:0)

我创建了一个迷你用户界面,它会根据正确的答案进行用户答案检查,如果答案是正确的,它将添加到分数并显示弹出窗口,说明它是正确的。测试一下,看看这是不是你想要的。

将其复制并粘贴到python中并测试它:

from tkinter import *
import tkinter as tk

class Application(Frame):
    def __init__ (self, master):
        Frame.__init__(self,master)
        self.grid()

        self.answers=['a','b','c','d']
        self.score = 0

        q1 = Label(self, text ="What is the answer?")
        q1.grid(row=0, column = 0)

        a1 = Button(self, text = self.answers[0], command = lambda: self.checkAnswer(self.answers[0]))
        a1.grid(row=1, column=0)

        a2 = Button(self, text = self.answers[1], command = lambda: self.checkAnswer(self.answers[1]))
        a2.grid(row=1, column=1)

        a2 = Button(self, text = self.answers[2], command = lambda: self.checkAnswer(self.answers[2]))
        a2.grid(row=2, column=0)

        a2 = Button(self, text = self.answers[3], command = lambda: self.checkAnswer(self.answers[3]))
        a2.grid(row=2, column=1)

    def checkAnswer(self, answer):
        if answer == self.answers[0]:
            self.score += 1
            self.correct()
        else:
            self.wrong()

    def correct(self):
        self.popup = tk.Tk()
        self.popup.wm_title("Correct!!!")

        label = tk.Label(self.popup,text=("Correct answer, your score is:",self.score))
        label.pack()
        self.popup.mainloop()

    def wrong(self):
        self.popup = tk.Tk()
        self.popup.wm_title("wrong")
        label = tk.Label(self.popup,text=("wrong answer"))
        label.pack()
        self.popup.mainloop()

root = tk.Tk()
app = Application(root)
root.mainloop()

如果您不明白,请随时问我。