Я создаю список data
со словарями, в которых есть вопрос, ответы и правильный ответ.
А затем я создаю окно с пустыми кнопками и метками и использую функцию set_next_question()
, чтобы получить вопрос для data
и использовать его для установки текста в кнопках и метках.
Кнопки запускают функции, которые проверяют правильность ответа, и запускают set_next_question()
, чтобы получить следующий вопрос из data
, и используют его для установки текста в кнопках иЭтикетки. Таким образом, следующий вопрос не должен ждать.
В IDLE
вам не нужно использовать window.mainloop()
, потому что IDLE
создается с tkinter
, и он запускает собственный window.mainloop()
, но обычноВы должны использовать window.mainloop()
для запуска вашей программы.
import tkinter as tk
data = [
{
'question': 'Which of these is not a capital city of South Africa',
'answers': ['Johannesburg', 'Bloemfontein', 'Cape Town', 'Pretoria'],
'correct': 0 # 'Johannesburg'
},
{
'question': 'What is the river that runs through London, England',
'answers': ['Dunaj', 'Nil', 'Tamiza', 'Yellow River'],
'correct': 2, # 'Tamiza'
}
]
def buttonA_action():
global score
if current_question['correct'] == 0:
score += 1
label_score['text'] = 'score: {}'.format(score)
set_next_question()
def buttonB_action():
global score
if current_question['correct'] == 1:
score += 1
label_score['text'] = 'score: {}'.format(score)
set_next_question()
def buttonC_action():
global score
if current_question['correct'] == 2:
score += 1
label_score['text'] = 'score: {}'.format(score)
set_next_question()
def buttonD_action():
global score
if current_question['correct'] == 3:
score += 1
label_score['text'] = 'score: {}'.format(score)
set_next_question()
def set_next_question():
global next_question_id
global current_question
if next_question_id >= len(data):
print('end score:', score)
window.destroy()
quit()
current_question = data[next_question_index]
label_question['text'] = current_question['question']
buttonA['text'] = current_question['answers'][0]
buttonB['text'] = current_question['answers'][1]
buttonC['text'] = current_question['answers'][2]
buttonD['text'] = current_question['answers'][3]
next_question_index += 1
# --- mian ---
next_question_index = 0
current_question = None
score = 0
window = tk.Tk()
label_question = tk.Label(window, text='')
buttonA = tk.Button(window, text='', command=buttonA_action)
buttonB = tk.Button(window, text='', command=buttonB_action)
buttonC = tk.Button(window, text='', command=buttonC_action)
buttonD = tk.Button(window, text='', command=buttonD_action)
label_score = tk.Label(window, text='score: 0')
label_question.pack()
buttonA.pack(fill='x', expand=True)
buttonB.pack(fill='x', expand=True)
buttonC.pack(fill='x', expand=True)
buttonD.pack(fill='x', expand=True)
label_score.pack()
set_question()
window.mainloop()
Кстати: действия кнопок очень похожи - только одно число отличается во всех функциях - поэтому они могут использовать одну и ту же функциюс другим аргументом
def action(number):
global score
if current_question['correct'] == number:
score += 1
label_score['text'] = 'score: {}'.format(score)
set_next_question()
def buttonA_action():
action(0)
def buttonB_action():
action(1)
def buttonC_action():
action(2)
def buttonD_action():
action(3)
Или даже использовать lambda
для присвоения command=
функции с аргументом:
buttonA = tk.Button(window, text='', command=lambda:action(0))
buttonB = tk.Button(window, text='', command=lambda:action(0))
buttonC = tk.Button(window, text='', command=lambda:action(0))
buttonD = tk.Button(window, text='', command=lambda:action(0))