我正在制作一個 /quiz 應用程式并將 100 個問題和答案存盤在 .json 檔案中,但我只想顯示 20 個隨機問題。
我收到錯誤“串列索引超出范圍”
這怎么樣?
這是我的代碼:
import random
import json
from tkinter import *
from itertools import zip_longest
import functools
percent = 0
level = 1
level_name = 0
glasses = 0
qno = 0
correctanswer_list = ['Well done!', 'Keep it up!', 'Cool!','Right!']
wronganswer_list = ['Wrong!', 'Better luck \nnext time!', 'Incorrect!']
question_number = [
"QUESTION NO. 1",
"QUESTION NO. 2",
"QUESTION NO. 3",
"QUESTION NO. 4",
"QUESTION NO. 5",
"QUESTION NO. 6",
"QUESTION NO. 7",
"QUESTION NO. 8",
"QUESTION NO. 9",
"QUESTION NO. 10",
"QUESTION NO. 11",
"QUESTION NO. 12",
"QUESTION NO. 13",
"QUESTION NO. 14",
"QUESTION NO. 15",
"QUESTION NO. 16",
"QUESTION NO. 17",
"QUESTION NO. 18",
"QUESTION NO. 19",
"QUESTION NO. 20"]
number_question_list = []
with open('questionanswer.json','r',encoding="utf8") as ques_ans_file:
ques_ans = json.load(ques_ans_file)
with open('highscore.json','r') as score_file:
scores = json.load(score_file)
root = Tk()
root.title('MMW Quiz App')
root.geometry('300x500')
def welcome():
global name
lbl_name1 = Label(text = 'Mathematics in the \nModern World \nQuiz App',font=("Trebuchet ms", 15))
lbl_name1.place(x=55,y=75)
lbl_name2 = Label(text= 'Please enter your name:', font=('Verdana',10))
lbl_name2.place(x=65,y=250)
name = StringVar()
name_entry = Entry(textvariable = name, width=30)
name_entry.place(x=55,y=280)
def destroy():
root.destroy()
def clear(root):
for element in root.winfo_children():
element.destroy()
def menu():
clear(root)
start_btn = Button(text = 'Start',
width= 15,
height = 1,
font=("Trebuchet ms", 10),
command = functools.partial(quiz,percent,level,level_name))
start_btn.place(x=90,y=160)
btnLeaderboards = Button(
root,
text="Leaderboards",
font=("Trebuchet ms", 10),
width=15,
height=1,
command = records
)
btnLeaderboards.place(x=90,y=220)
btnCredits = Button(
root,
text="Credits",
font=("Trebuchet ms", 10),
width=15,
height=1,
command = credits)
btnCredits.place(x=90, y=280)
btnQuit = Button(
root,
text="Quit",
font=("Trebuchet ms", 10),
width=15,
height=1
)
btnQuit.place(x=90, y=340)
我不知道這是不是錯誤的
def shuff_ques():
i = 0
while len(number_question_list) != len(ques_ans[level]):
number_question_list.append(str(i))
i = 1
random.shuffle(number_question_list)
shuff_ques()
prcnt = 100/len(number_question_list)
def quiz(percent,level,level_name):
clear(root)
global glasses,que_1
ques_lbl = Label(text=question_number[0], font = ("Verdana",15))
ques_lbl.place(x = 80, y = 30)
correct_lbl1 = Label(text = "Score: " str(percent),font = ("Verdana",10))
correct_lbl1.place(x = 230,y=5)
if len(number_question_list) == 0:
clear(root)
que_1 = ''
if percent > 9:
if que_1 == 9:
w_lbl = Label(text = 'Good Job, you finish all the questions. \nYou got ' str(percent) '!',
font = ("Verdana",20))
w_lbl.pack(pady=(60,30))
h_button = Button(text = 'Home',
font = ("Verdana",15),
width = 15,
height = 1,
command= menu)
h_button.place(x=15, y=450)
scores.append([name.get(), glasses])
scores.sort(key=lambda x:x[1])
scores.reverse()
scores.update()
else:
scores.append([name.get(), glasses])
scores.sort(key=lambda x: x[1])
scores.reverse()
scores.update()
res_lbl = Label(text ='Good Job, you finish all the questions. \nYou only got ' str(percent) '!',
font = ("Verdana",20))
res_lbl.pack(pady=(0,40))
h1_button = Button(text='Home',
font=("Verdana", 15),
width=15,
height=1,
command=menu)
h1_button.place(x=15, y=450)
n = 75
question = ques_ans[level][int(number_question_list[0])][0]
global qno
ques_lbl.configure(text=question_number[qno])
qno = 1
def split_str(que,n):
args = [iter(que)] * n
for s in zip_longest(*args, fillvalue=''):
yield ''.join(s)
correct_lbl1 = Label(text = 'Score: ' str(percent),
font=("Verdana", 10))
correct_lbl1.place(x = 230, y =5)
que_1 = ' '
for s in split_str(question, n):
que_1 = s '\n'
question_label = Label(
text=('\n' que_1),
font=("Verdana", 10)
)
question_label.pack(pady=(80, 100))
def yes_no(percent,level):
global glasses,right_answer
clear(root)
if r_var.get() == right_answer:
glasses = prcnt
percent = prcnt
right_answer = Label(text = random.choice(correctanswer_list),
font = ("Verdana", 15))
right_answer.place(x = 110, y = 100)
correct_lbl1 = Label(text = 'Score: ' str(percent),
font = ("Verdana",10))
correct_lbl1.place(x=230, y =5)
else:
wrong_ans = Label(text = random.choice(wronganswer_list),
font = ("Verdana",15))
wrong_ans.place(x = 110, y = 100)
correct_lbl1 = Label(text='Score: ' str(percent),
font=("Verdana", 10))
correct_lbl1.place(x=230, y=5)
check_button.destroy()
ques_lbl.destroy()
option_1.destroy()
option_2.destroy()
option_3.destroy()
option_4.destroy()
if len(number_question_list) == 0:
w_lbl = Label(text='Good Job, you finish all the questions. \nYou got ' str(percent) '!',
font=("Verdana", 20))
w_lbl.place(x = 80, y = 90)
else:
nxt_btn = Button(text = 'Next Question',
font = ("Verdana",10),
width = 15,
height = 1,
command = functools.partial(quiz,percent,level,level_name))
nxt_btn.place(x = 90, y =280)
choices = ques_ans[level][int(number_question_list[0])][1]
r_var = IntVar()
option_1 = Radiobutton(text = choices[0],
font = ("Verdana", 10),
variable = r_var,
value = 0)
option_1.place(x=30, y=150)
option_2 = Radiobutton(text=choices[1],
font=("Verdana", 10),
variable=r_var,
value=1)
option_2.place(x=30, y=180)
option_3 = Radiobutton(text=choices[2],
font=("Verdana", 10),
variable=r_var,
value=2)
option_3.place(x=30, y=210)
option_4 = Radiobutton(text=choices[3],
font=("Verdana", 10),
variable=r_var,
value=3)
option_4.place(x=30, y=240)
global right_answer
right_answer = ques_ans[level][int(number_question_list[0])][2]
number_question_list.pop(0)
check_button = Button(text = "Verify",
height = 1,
width = 15,
command = functools.partial(yes_no,percent,level))
check_button.place(x = 90, y = 450)
root.mainloop()
def records():
def delete_score():
scores.clear()
menu()
clear(root)
record_label = Label(text='Records',
font = ("Verdana", 15))
record_label.pack()
if len(scores) > 5:
del scores[5:]
if len(scores) > 0:
score = 0
while score != len(scores):
score_lbl = Label(text = '\n' str((score 1)) '. ' (scores[score][0] ' ' str(scores[score][1])),
font = ("Verdana",10))
score_lbl.pack()
score = 1
clear_score_btn = Button(text = 'Clear Records',
font = ("Verdana",10),
height = 1,
width = 15,
command = functools.partial(delete_score))
clear_score_btn.place(x = 20,y = 450)
back_btn = Button(text='Back',
font=("Verdana", 10),
height=1,
width=15,
command=menu)
back_btn.place(x=80, y=450)
def credits():
clear(root)
lbltxtCredits = Label(root,
text = 'Credits',
font = ("Verdana",15))
lbltxtCredits.pack(pady=10)
labeltextCredits = Label(root,
text='Team 9 \n\nArellano, Jayven\n\nChavez,Ivan Louige\n\nDelos Santos, Thea\n\nMelivo,Angel',
font=("Verdana", 15))
labeltextCredits.pack(pady=10)
btnBack = Button(root,
text="Back",
font=("Verdana", 10),
height = 3,
width = 15,
command=menu)
btnBack.place(x=10, y=430)
enter_btn = Button(text='Enter', width = 10, height = 1, command=menu)
enter_btn.place(x=110,y=330)
welcome()
root.mainloop()
with open('highscore.json','w') as score_file:
json.dump(scores,score_file)
這是我的 .json 檔案,我目前仍在添加 100 個問題。
["Mathematics in the Modern World",
[["Regular, recurring, and repeating \nforms or designs that are commonly \nobserved in natural objects",
["Sequence", "Patterns", "Variables", "Fibonacci Sequence"], 1],
["Ordered list of numbers called \nterms; it may have repeated values; the \narrangement of these terms is set by a definite rule",
["Variables","Fibonacci Sequence ","Patterns","Sequence"], 3],
["Placeholder; quantity that may \nchange within the context mathematically \nor in experiments.",
["Fibonacci Sequence", "Variables","Sequence","Patterns"], 1],
["Performed by adding the two \npreceding numbers starting from 0 and 1",
["Patterns","Fibonacci Sequence","Sequence","Variables"],1],
["Well defined collection of \ndistinct objects",
["Subset","Set","Proper Subset","Proper Set"],1],
["Basic relation of the set is by \nof subset",
["Subset","Set","Proper Subset","Proper Set"],0],
["Atleast one is a Subset",
["Subset","Set","Proper Subset","Proper Set"],2],
["All things of the given property \nis true",
["Universal Statement","Conditional Statement","Existential Statement","Statement"],0],
["If one thing is true, then the \nother also has to be true",
["Conditional Statement","Existential Statement","Universal Statement","Statement"],0],
["There is at least one thing which \nthe property is true",
["Existential Statement","Universal Statement","Conditional Statement","Statement"],0],
["\"For all\" and \"If-Then\"",
["Existential Universal Statement","Universal Conditional Statement","Universal Existential Statement","Existential Statement"],1],
["First part asserts that a certain \nobject exist and is universal, \nbecause the second part says that the first part satisfies a property",
["Universal Existential Statement","Existential Universal Statement","Universal Conditional Statement","Existential Statement"],1],
["The first part tells that a certain \nproperty is true for all objects",
["Universal Conditional Statement","Universal Existential Statement","Existential Universal Statement","Existential Statement"],1],
["From specific to general; process \nof reaching a general conclusion by \nexamining specific examples.",
["Deductive Reasoning","Inductive Reasoning","Conditional Statement","Existential Statement"],1],
["From general to specific; general \nassumptions,procedure and principles",
["Deductive Reasoning","Inductive Reasoning","Conditional","Existential"],0],
["It is defined as the study of \npatterns, numbers and arithmetic operations.",
["Discrete Mathematics","Mathematics","Geometry","Trigonometry"],1],
["What is the 20th term of the \nnumber sequence; \n8; 16; 24; 32; …?",
["140","150","160","170"],2],
["What is the 20th term of the \nsequence of number \n2; 5; 10; 17; 26; 37; …?",
["301","401","501","601"],1],
["It is an ordered list of \nnumbers, called terms that may have repeated values.",
["Pattern","Sequence","Set","Reccurence Design"],1],
["It is a regular, repeated, \nor recurring forms or designs.",
["Shape","Design","Forms","Pattern"],3],
["Considered to be the most \ntalented Western Mathematician of the Middle Ages",
["Albert Einstein","Pythagoras","Leonardo Fibonacci","Plato"],2],
["The Fibonacci numbers also \nhave a geometric manifestation in the form of:",
["Pattern","Sequence","Common Ratio","Golden Ratio"],3],
["Which number is next in the \nFibonacci sequence of numbers: 1, 1, 2, 3, 5, 8, 13, 21..",
["55","59","34","44"],2],
["Which of the following is NOT \nan example of Fibonacci numbers found in nature?",
["Pinecone Spiral","Number of petails in daisy","A mountain range","Spiral on the sunflower"],2],
["What is one way to decide if \ntwo numbers follow a Fibonacci sequence?",
["If their sum is as the same as their difference","If their ratio is approximately the golden ratio","If each number is an odd number","If the product is a prime number"],1],
["Correct arrangement of \nmathematical symbols",
["Simpler expression","Expression","Mathematical expression","Simple Mathematical"],2],
["Which is not a Characteristics \nof mathematics?",
["Precise","Range","Concise","Powerful"],1],
["The product of ten and y",
["10 y","10y","y|10","y-10"],1],
["Twenty decreased by a number t",
["t - 20","20 - t","20 t","-(20 - t)"],1],
["Four times the sum of twelve and y",
["12y 4","4(12 y)","(12 y) - 4","4(12 - y)"],1]]
]
uj5u.com熱心網友回復:
問題是qno不斷增加超過question_number陣列的長度。
你需要做這樣的事情:
global qno
if qno < len(question_number):
ques_lbl.configure(text=question_number[qno])
qno = 1
else:
# show notification that the quiz is over
# e.g. message box with the final score
qno = 0
menu()
return
順便說一句,我喜歡你的測驗(不是我做得特別好,但問題很有趣??)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/375690.html
