Есть ли способ заставить два блока кода идти один за другим - PullRequest
0 голосов
/ 12 октября 2019

Я пытаюсь сделать что-то, где у меня есть куча вопросов, которые задают один за другим, и у меня есть проблема, с которой я продолжаю сталкиваться. Когда я задаю только один вопрос, он работает очень хорошо, но когда я добавляю другой вопрос, это происходит. Кстати, я делаю это в IDLE.

Which of these is not a capital city of South Africa
What is the river that runs through London, England

Появляется в окне оболочки, но оба до того, как он делает кнопки, поэтому к моменту появления кнопок ваш экран загружается кучей графических интерфейсов и текста. Почему он это делает?

a = list()
print('Which of these is not a capital city of South Africa')
from time import sleep
sleep(5)
from tkinter import *
#The buttons are the possible answers
def bAaction():
    print('TRUE!')
    a.append(1)
    print('score')
    b = sum(a)
    print(b)
    window.destroy()
def bBaction():
    print('False')
    a.append(0)
    print('score')
    b = sum(a)
    print(b)
    window.destroy()
def bCaction():
    print('False')
    a.append(0)
    print('score')
    b = sum(a)
    print(b)
    window.destroy()
def bDaction():
    print('False')
    a.append(0)
    print('score')
    b = sum(a)
    print(b)
    window.destroy()
window = Tk()
buttonA = Button(window, text='Johannesburg', command=bAaction)
buttonB = Button(window, text='Bloemfontein', command=bBaction)
buttonC = Button(window, text='Cape Town', command=bCaction)
buttonD = Button(window, text='Pretoria', command=bDaction)
buttonA.pack()
buttonB.pack()
buttonC.pack()
buttonD.pack()
from time import sleep
sleep(5)

У меня тогда был бы другой вопрос, тот же, но с другими ответами и т. Д. С другим вопросом.

Ожидаемый результат - показатьвопрос с возможными ответами, а затем подождите 5 секунд.

Если вы знаете, как? Было бы здорово, если бы вы объяснили мне, как заставить второй вопрос ждать, пока не будет нажата кнопка. Спасибо за любую помощь.

1 Ответ

0 голосов
/ 14 октября 2019

Я создаю список 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))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...