tkinter按钮功能后返回回路

2024-09-30 02:23:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我想让我的测试等待用户与不同值的按钮交互,然后决定按钮内的“文本”是否与问题的答案匹配。这个系统可以工作,但不是等待用户选择一个选项。它通过所有的问题输出所有的答案和问题,不需要交互

我尝试使用partiallambda让它在用户按下某个按钮后进入函数,它工作了,但它不接受按钮按下,并且处理所有问题。线程基本上做了相同的事情,但只停留在第一个问题上,并在没有用户交互的情况下显示每个选项的一百万个弹出窗口

是否有更简单的方法来执行此操作,并允许功能查看按下了哪个按钮,或者我是否正确执行了此操作

listofdifnumbers包含所有困难的问题编号,因此假设用户选择了10个简单、20个正常和30个困难的问题,那么listofdifnumbers将是[10,20,30]

questions包含嵌套字典形式的所有问题,例如{1: {'Question': 'WWW stands for?', 'fakes': 'World Word Web', 'Answer': 'World Wide Web'}, 2: {'Question': 'Which of the following is a group of independent computers attached to one another through communication media', 'fakes': 'Internet', 'Answer': 'Network'}}

def wrongcheck(num):
    global  Questionnum, questionseasy1, questionsmedium1, questionshard1,answer,score
    global choice, correctorwrong
    global score1of1

    if score1of1<=listofdifnumbers[0]:
        if num == 1:
            if showeasybutton1["text"]== questions[score1of1].get("Answer"):
                picked = showeasybutton1["text"]
                choice.append(picked)
                correctorwrong.append("correct")
                error.showerror("Correct",("%s is the correct answer \n Welldone \n Score +1"%(picked)),icon="info")
                score+=1
            else:
                picked = showeasybutton1["text"]
                choice.append(picked)
                correctorwrong.append("Wrong")
                error.showerror("Wrong",("%s was the correct answer,\n You chose %s"%(questions[score1of1].get("Answer"),picked)),icon="info")
        elif num == 2:
            if showeasybutton2["text"]== questions[score1of1].get("Answer"):
                picked = showeasybutton2["text"]
                choice.append(picked)
                correctorwrong.append("correct")
                error.showerror("Correct",("%s is the correct answer \n Welldone \n Score +1"%(picked)),icon="info")
                score+=1
            else:
                picked = showeasybutton2["text"]
                choice.append(picked)
                correctorwrong.append("Wrong")
                error.showerror("Wrong",("%s was the correct answer,\n You chose %s"%(questions[score1of1].get("Answer"),picked)),icon="info")

        print(correctorwrong)
        print(choice)
        print(score1of1)


def quizinterfacestarter():
    global timer
    global login
    global login, lookwhereat2,quizconfigurationframe, AllquizSTATSlabel
    global  Questionnum, questionseasy1, questionsmedium1, questionshard1, MaxMarkss, MaxMarks
    global questions

    print(questions)
    print(len(questions))
    screen_width = login.winfo_screenwidth()
    screen_height = login.winfo_screenheight()
    for widget in login.winfo_children():
        widget.destroy()
    height1 = int(screen_height)/4
    height2 = int(screen_height)*3
    tophalfframe= Frame(login,width=int(screen_width),height=height1,bg="light coral")
    tophalfframe.grid(sticky="new")
    goback= PhotoImage(file='icons/goback.png')
    exitframebutton= Button(tophalfframe,image=goback,text="Return     ",compound="left",bg='aquamarine',relief='flat', font="Ariel 25",command=subjectgoback)
    exitframebutton.grid(column=1,sticky="nws")
    movealonglabel = Label(text="                                       ",bg="light coral")
    movealonglabel.grid(row=1,column=2,columnspan=2)
    QuestionLabelAsker = Label(tophalfframe,text="Questions Loading ...",relief='raised', font="Ariel 20")
    QuestionLabelAsker.grid(column=5,row=1,columnspan=7)
    if timer == True:
        initiatetimerstart = time.strftime("%H:%M:%S")
    global fsos,showeasybutton1,showeasybutton2,answer
    showeasybutton1=Button(login,text="Answer 1",font="Ariel 30")
    showeasybutton1.grid(sticky="new")
    showeasybutton2=Button(login,text="Answer 2",font="Ariel 30")
    showeasybutton2.grid(sticky="new")
    showmediumbutton=Button(login,text="Answer 3",font="Ariel 30")
    showmediumbutton.grid(sticky="new")
    showhardbutton=Button(login,text="Answer 4",font="Ariel 30")
    showhardbutton.grid(sticky="new")
    global choice, correctorwrong,score
    choice = []
    correctorwrong =[]
    score=0
    sonumisone=0
    global score1of1
    score1of1=0
    ##works up to here
    while sonumisone != (sum(listofdifnumbers)+1):
        sonumisone+=1
        if sonumisone<=listofdifnumbers[0]:
            score1of1+=1
            QuestionLabelAsker["text"]=questions[score1of1].get("Question")
            answers = [questions[score1of1].get("fakes"),questions[score1of1].get("Answer")]
            fsos = r.choice(answers)
            showeasybutton1["text"]= fsos
            answers.remove(fsos)
            showeasybutton2["text"]= answers[0]
            showeasybutton2.config(command=lambda *args: wrongcheck(2))
            showeasybutton1.config(command=lambda *args: wrongcheck(1))
            showmediumbutton["state"]="disabled"
            showhardbutton["state"]="disabled"

    login.mainloop()

Tags: textanswergetloginglobalgridquestionschoice
2条回答

考虑到您告诉我的内容,我将整个问题提取器移动到一个新函数,并将while语句更改为if语句,这正是我想要的。感谢所有回答的人

def wrongcheck(num):
    global  Questionnum, questionseasy1, questionsmedium1, questionshard1,answer,score
    global choice, correctorwrong
    global score1of1
    login.update()
    if score1of1<=listofdifnumbers[0]:
        if num == 1:
            if showeasybutton1["text"]== questions[score1of1].get("Answer"):
                picked = showeasybutton1["text"]
                choice.append(picked)
                correctorwrong.append("correct")
                error.showerror("Correct",("%s is the correct answer \n Welldone \n Score +1"%(picked)),icon="info")
                score+=1
            else:
                picked = showeasybutton1["text"]
                choice.append(picked)
                correctorwrong.append("Wrong")
                error.showerror("Wrong",("%s was the correct answer,\n You chose %s"%(questions[score1of1].get("Answer"),picked)),icon="info")  
        elif num == 2:
            if showeasybutton2["text"]== questions[score1of1].get("Answer"):
                picked = showeasybutton2["text"]
                choice.append(picked)
                correctorwrong.append("correct")
                error.showerror("Correct",("%s is the correct answer \n Welldone \n Score +1"%(picked)),icon="info")
                score+=1
            else:
                picked = showeasybutton2["text"]
                choice.append(picked)
                correctorwrong.append("Wrong")
                error.showerror("Wrong",("%s was the correct answer,\n You chose %s"%(questions[score1of1].get("Answer"),picked)),icon="info")
    print(correctorwrong)
    print(choice)
    print(score1of1)
    fixquizinterfaceproblem()


def fixquizinterfaceproblem():
    global timer
    global login, lookwhereat2,quizconfigurationframe, AllquizSTATSlabel
    global  Questionnum, questionseasy1, questionsmedium1, questionshard1, MaxMarkss, MaxMarks
    global questions
    global sonumisone,score1of1,score
    if sonumisone != (sum(listofdifnumbers)+1):
        sonumisone+=1
        print(score1of1,sonumisone)
        if sonumisone<=listofdifnumbers[0]:
            score1of1+=1
            login.update()
            QuestionLabelAsker["text"]=questions[score1of1].get("Question")
            answers = [questions[score1of1].get("fakes"),questions[score1of1].get("Answer")]
            fsos = r.choice(answers)
            showeasybutton1["text"]= fsos
            answers.remove(fsos)
            showeasybutton2["text"]= answers[0]
            showeasybutton2.config(command=lambda *args: wrongcheck(2))
            showeasybutton1.config(command=lambda *args: wrongcheck(1))
            showmediumbutton["state"]="disabled"
            showhardbutton["state"]="disabled"
    else:
        pass
    login.mainloop()

            
def quizinterfacestarter():
    global timer
    global login
    global login, lookwhereat2,quizconfigurationframe, AllquizSTATSlabel
    global  Questionnum, questionseasy1, questionsmedium1, questionshard1, MaxMarkss, MaxMarks
    global questions
    print(questions)
    print(len(questions))         
    screen_width = login.winfo_screenwidth()
    screen_height = login.winfo_screenheight()
    for widget in login.winfo_children():
        widget.destroy()
    height1 = int(screen_height)/4
    height2 = int(screen_height)*3
    tophalfframe= Frame(login,width=int(screen_width),height=height1,bg="light coral")
    tophalfframe.grid(sticky="new")
    goback= PhotoImage(file='icons/goback.png')
    exitframebutton= Button(tophalfframe,image=goback,text="Return     ",compound="left",bg='aquamarine',relief='flat', font="Ariel 25",command=subjectgoback)
    exitframebutton.grid(column=1,sticky="nws")
    movealonglabel = Label(text="                                       ",bg="light coral")
    movealonglabel.grid(row=1,column=2,columnspan=2)
    global QuestionLabelAsker
    QuestionLabelAsker = Label(tophalfframe,text="Questions Loading ...",relief='raised', font="Ariel 20")
    QuestionLabelAsker.grid(column=5,row=1,columnspan=7)
    if timer == True:
        initiatetimerstart = time.strftime("%H:%M:%S")
    global fsos,showeasybutton1,showeasybutton2,showmediumbutton, showhardbutton, answer
    showeasybutton1=Button(login,text="Answer 1",font="Ariel 30")
    showeasybutton1.grid(sticky="new")
    showeasybutton2=Button(login,text="Answer 2",font="Ariel 30")
    showeasybutton2.grid(sticky="new")
    showmediumbutton=Button(login,text="Answer 3",font="Ariel 30")
    showmediumbutton.grid(sticky="new")
    showhardbutton=Button(login,text="Answer 4",font="Ariel 30")
    showhardbutton.grid(sticky="new")
    global choice, correctorwrong,score
    choice = []
    correctorwrong =[]    
    score=0
    global sonumisone
    sonumisone=0
    global score1of1
    score1of1=0
    fixquizinterfaceproblem()
    login.mainloop()

我知道你可能对重新开始不感兴趣,但下面是我如何实施这样一个计划的。脚本的主要入口点是main函数,它定义了一个“问题对象”(实际上只是字典)列表,描述所有问题及其相关答案。本例总共只有两个问题,每个问题有四个可能的答案。我们实例化Application类的一个实例,并运行它的.mainloop()来启动事件循环。应用程序实例用我们的问题列表初始化。它不直接跟踪问题列表,而是创建该列表的迭代器,以便我们以后可以使用next对问题进行迭代。整个程序以事件驱动的方式工作——首先,我们创建小部件并设置布局。然后,我们调用goto_next_question从问题迭代器中获取下一个问题,然后填充标签和按钮的文本。我们还更改了所有按钮的回调,这样只有一个按钮会引导我们进入下一个问题。当用户按下带有正确答案的按钮时,我们再次调用goto_next_question,并以这种方式继续,直到没有问题为止:

import tkinter as tk


class Application(tk.Tk):

    def __init__(self, questions, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.title("Questions")
        self.geometry("256x128")
        self.resizable(width=False, height=False)

        self.grid_columnconfigure(0, weight=1)
        self.grid_columnconfigure(1, weight=1)
        self.grid_rowconfigure(0, weight=1)
        self.grid_rowconfigure(1, weight=1)
        self.grid_rowconfigure(2, weight=1)

        self.questions = iter(questions)

        self.question_label = tk.Label(self, text="hello world" * 3, borderwidth=2, relief="ridge")
        self.question_label.grid(row=0, column=0, columnspan=2)

        self.default_button_color = tk.Button().cget("bg")

        self.buttons = []
        for y in range(2):
            for x in range(2):
                button = tk.Button(self, text="123")
                button.grid(row=y+1, column=x, sticky=tk.N + tk.S + tk.E + tk.W)
                self.buttons.append(button)

        self.goto_next_question()

    def goto_next_question(self):
        from random import shuffle
        
        question = next(self.questions, None)
        if question is None:
            self.destroy()
            return
        shuffle(question["answers"])
        
        self.question_label["text"] = question["text"]
        for button, answer in zip(self.buttons, question["answers"]):
            button["text"] = answer["text"]
            button["bg"] = self.default_button_color
            if answer["isCorrect"]:
                button["command"] = self.goto_next_question
            else:
                button["command"] = lambda button=button: self.answered_wrong(button)

    def answered_wrong(self, button):
        from tkinter.messagebox import showerror
        button["bg"] = "red"
        showerror(message="Wrong!")


def main():

    questions = [
        
        {
            "text": "What is the capitol of Switzerland?",
            "answers": [
                {
                    "text": "Bern",
                    "isCorrect": True
                },
                {
                    "text": "Zürich",
                    "isCorrect": False
                },
                {
                    "text": "Lucerne",
                    "isCorrect": False
                },
                {
                    "text": "Geneva",
                    "isCorrect": False
                }
            ]
        },

        {
            "text": "What is the height of Mount Everest?",
            "answers": [
                {
                    "text": "8,849m",
                    "isCorrect": True
                },
                {
                    "text": "7,994m",
                    "isCorrect": False
                },
                {
                    "text": "4,021m",
                    "isCorrect": False
                },
                {
                    "text": "10,119m",
                    "isCorrect": False
                }
            ]

        }
    ]

    application = Application(questions)
    application.mainloop()

    return 0


if __name__ == "__main__":
    import sys
    sys.exit(main())

相关问题 更多 >

    热门问题