这应该让您开始了解我认为您应该如何进行。
data = {question:[id,answer]}
# So it would be like
data = {'Who was the first prime minister of india?':[1,'Jawaharlal Nehru'],
'Tallest building in the world':[2,'Burj Khalifa'],
'Largest country in the world':[3,'Russia']}
- 创建文件explanation.txt,然后将id和explanation存储为:
id - explanation
- 所以解释的文本文件(explnation.txt)应该是这样的:
1 - Your explanation goes here: Tryst with destiny
2 - UAE
3 - WC 2018
import tkinter as tk
import random
root = tk.Tk()
# Store it here
data = {'Who was the first prime minister of india?':[1,'Jawaharlal Nehru'],
'Tallest building in the world':[2,'Burj Khalifa'],
'Largest country in the world':[3,'Russia']}
score = 0 # Score of correct answers
def get_question():
global id, answer, explanation
exp_label.config(text='') # Clear the previous explanation
question = random.choice(list(data.keys())) # Get the question
item = data[question] # Get the corresponding list
id = item[0] # Get the id from the list
answer = item[1] # Get the answer from the list
explanation = get_explanation(id) # Find the explanation using the id
q_label.config(text=question) # Update the question to this
def submit():
global score
if answer_ent.get().lower() == answer.lower(): # If correct answer
score += 1 # Increase the score by 1
score_label.config(text=f'Score: {score}') # Update the score label
else: # If wrong answer
exp_label.config(text=explanation) # Show the explanation
answer_ent.delete(0,'end') # Clear the entry
def get_explanation(id):
with open('explanation.txt','r') as file: # Open the file
lst = file.readlines() # Read each line and make it a list
for i in lst: # Looping through that list
fetched_id = i.split(' - ')[0] # Split the txt with ' - ' and get the id
if int(fetched_id) == id: # If fetched and our question id are same
explanation = i.split(' - ')[1][:-1] # Get the explanation and trim the \n
return explanation # Return it
q_label = tk.Label(root,font=(0,21))
q_label.grid(row=0,column=0)
answer_ent = tk.Entry(root)
answer_ent.grid(row=1,column=0,pady=10,padx=20)
exp_label = tk.Label(root,font=(0,13))
exp_label.grid(row=3,column=0,pady=10)
score_label = tk.Label(root,text='Score: 0',font=(0,13))
score_label.grid(row=4,column=0)
tk.Button(root,text='Submit',command=submit).grid(row=5,column=0,pady=10)
tk.Button(root,text='Next',command=get_question).grid(row=6,column=0,pady=10)
get_question() # Call the function immediately
root.mainloop()
我已经使用 cmets 解释了代码,以便在旅途中理解它。这只是一个小规模示例,您可以采用和扩展更多功能,例如确保没有重复相同的问题等等。使用tkinter,这种方式对我来说似乎很容易。