PySimpleGui - 有没有办法清空屏幕?

PySimpleGui - is there a way to empty the screen?

我正在制作一个测验应用程序,当所有问题都得到回答后,我希望显示完整的文本,而没有任何输入字段或来自先前状态的文本。我正在考虑使用一个不可见的选项卡,在回答问题或清除所有文本并使新文本出现在末尾之前,用户无法单击该选项卡。有没有比这两种更好的方法?如果不是,哪个更好?

gui

import PySimpleGUI as sg
import json

data = {
    "question": [
        "Q1. What equation for force",
        "Q2. Define isotope",
        "Q3. Define wavelength",
        "Q4. Define modal dispersion"
    ],
    "answers": [

        "f=ma",
        "isotopes are atoms of the same element but with a different number of neutrons",
        "the least distance between adjacent particles which are in phase",
        "causes light travelling at different angles to arrive at different times"

    ],
    "automark": [
        ["F=ma", "f=ma", "F=MA"],
        ["same number of protons", "different number of neutrons", "same element"],
        ["minimum distance between adjacent particles", "particles which are in phase"],
        ["different angles", "different times"]
    ],
    "mastery": [
        0,
        0,
        0,
        0
    ],
    "incorrect": [
        0,
        0,
        0,
        0
    ]
}


def nextset(no, no2, do_not_stop, list1, list2):
    endlist = []  # number in the list represent question number
    while not do_not_stop:
        if no == 3:
            do_not_stop = True

        if list2[no] == list1[no2]:
            position = list1.index(list2[no])
            no += 1
            no2 = 0
            endlist.append(position)
            print(endlist)

        else:
            no2 += 1
    savetoexternal(endlist)


def savetoexternal(endlist):
    with open("savefile.json", 'w') as f:  # creates external json file to be read from later
        json.dump(endlist, f, indent=2)


# main program
def listdata(list1):
    do_not_stop = False
    no = 0
    no2 = 0
    list2 = list1.copy()
    list2.sort(
        reverse=True)  # ordered question from highest to lowest while keeping original intact to preserve question number
    print(list1)
    print(list2)
    nextset(no, no2, do_not_stop, list1, list2)


def main():
    # initialise the question, question number and answer
    question = data['question']
    answers = data['answers']
    automark = data['automark']
    mastery = data['mastery']
    incorrect = data['incorrect']
    q_no = 0
    max_q_no = 4

    sg.theme('DarkBlack')  # Adding colour
    # Stuff in side the window

    layout = [[sg.Text("                      "), sg.Text(question[0], key='_Q1_', visible=True),
               sg.Text(size=(60, 1), key='-OUTPUT-')],
              [sg.Text("correct answer:"), sg.Text(size=(60, 1), key='-OUTPUTA-')],
              [sg.Text("automark allows:"), sg.Text(size=(60, 1), key='-OUTPUTB-')],
              [sg.Text("your answer was:"), sg.Text(size=(60, 1), key='-OUTPUTC-')],
              [sg.Text('Answer here:   '), sg.InputText(size=(60, 1), key='-INPUT-', do_not_clear=False)],
              [sg.Button('Submit', key='b1'), sg.Button('Cancel'), sg.Button('Skip')]]

    # Create the Window
    window = sg.Window('Quiz', layout, size=(655, 565))
    # Event Loop to process "events" and get the "values" of the inputs
    while True:
        event, values = window.read()
        if event == sg.WIN_CLOSED or event == 'Cancel':  # if user closes window or clicks cancel
            break
        window['_Q1_'].Update(visible=False)
        window['-OUTPUT-'].update(question[q_no])
        select_not_mastered_question = True

        if all(x == 3 for x in mastery):
            print("all questions mastered")  # add to gui later
            list1 = []
            q_no = 0
            while q_no < max_q_no:
                list1.append(incorrect[q_no])
                q_no += 1
            q_no = 0
            listdata(list1)

        if values['-INPUT-'] == answers[q_no]:  # list index out of range occurs when all questions are complete, need to add completed screen by using else statement
            mastery[q_no] += 1  # need to add to gui
            print(mastery)
            q_no += 1
            if q_no == max_q_no:
                q_no = 0

            while select_not_mastered_question:  # make sures the next question has not already been mastered
                if mastery[q_no] == 3:
                    if q_no == max_q_no:
                        q_no = 0
                    q_no += 1
                else:
                    select_not_mastered_question = False

            print("current q_no:", q_no)

            window['-OUTPUT-'].update(question[q_no])  # accepts the answer as correct and moves onto the next question
            window['-OUTPUTA-'].update('')
            window['-OUTPUTB-'].update('')
            window['-OUTPUTC-'].update('')

        if values['-INPUT-'] in automark[q_no]:  # shows the answer was correct but missing some key points
            window['-OUTPUTA-'].update(answers[q_no])
            window['-OUTPUTB-'].update(automark[q_no])
            window['-OUTPUTC-'].update('partially correct')

        if event == 'Skip':
            q_no += 1
            if q_no == max_q_no:
                q_no = 0

            while select_not_mastered_question:  # make sures the next question has not already been mastered
                if mastery[q_no] == 3:
                    if q_no == max_q_no:
                        q_no = 0
                    q_no += 1
                else:
                    select_not_mastered_question = False

            window['-OUTPUT-'].update(question[q_no])  # moves onto the next question
            window['-OUTPUTA-'].update('')
            window['-OUTPUTB-'].update('')
            window['-OUTPUTC-'].update('')
            window['-INPUT-'].update(disabled=False)
            window['b1'].update(disabled=False)

        elif values['-INPUT-'] == '':
            print('answer was:', answers[q_no])  # for testing
            window['-OUTPUTA-'].update(
                answers[q_no])  # shows that the answer is incorrect and displays the right answer
            window['-OUTPUTB-'].update(automark[q_no])
            window['-OUTPUTC-'].update('incorrect')
            window['-INPUT-'].update(disabled=True)
            window['b1'].update(disabled=True)
            incorrect[q_no] += 1
            if mastery[q_no] == 0:
                print(mastery)
            else:
                mastery[q_no] -= 1
                print(mastery)

    window.close()


main()

这里我设置了两帧并且只有一帧同时可见

用户代码太长了,这里用我的代码来演示一下。 记得升级 PySimpleGUI,可能来自 github.

from random import randint
import PySimpleGUI as sg

def new_questions(number):
 return [(f'{i}x{j} = ?', f'{i*j}')
    for i, j in [(randint(1, 9), randint(1, 9)) for i in range(number)]]

font = ("Courier New", 16)
sg.theme("DarkBlue3")
sg.set_options(font=font)

number = 5

frame1 = [
    [sg.VPush()],
    [sg.Text("", key='Result')],
    [sg.Text("Ready to answer questions")],
    [sg.Button("Start"), sg.Button("Exit")],
    [sg.VPush()],
]

frame2 = [
    [sg.VPush()],
    [sg.Text("Question:"), sg.Text("",  size=7, key="Question")],
    [sg.Text("Answer:"),   sg.Input("", size=7, key="Answer")],
    [sg.Button("OK")],
    [sg.VPush()],
]

layout = [
    [sg.Frame("", frame1, size=(360, 200), visible=True,  key='Frame1',  element_justification='center'),
     sg.Frame("", frame2, size=(360, 200), visible=False, key='Frame2',  element_justification='center')],
]

window = sg.Window("Test", layout, finalize=True)
question, answer, result = window['Question'], window['Answer'], window['Result']
frame1, frame2 = window['Frame1'], window['Frame2']
answer.bind("<Return>", "-Return")
sg.theme("DarkGrey")

while True:

    event, values = window.read()

    if event in (sg.WINDOW_CLOSED, 'Exit'):
        break
    elif event == 'Start':
        frame2.update(visible=True)
        frame1.update(visible=False)
        index, correct = 0, 0
        questions = new_questions(number)
        q, a = questions[index]
        question.update(q)
        answer.update('')
        answer.set_focus()
    elif event in ('OK', "Answer-Return") and index < number:
        ans = values['Answer'].strip()
        index += 1
        if ans == a:
            correct += 1
            sg.popup(f"Your answer is correct ({correct}/{index})")
        else:
            sg.popup(f"Correct answer is {a} ({correct}/{index})")
        if index < number:
            q, a = questions[index]
            question.update(q)
            answer.update('')
            answer.set_focus()
        else:
            frame1.update(visible=True)
            frame2.update(visible=False)
            result.update(f"{correct}/{index} correct !!")

window.close()