测验游戏:python tkinter等待点击按钮继续执行代码然后退出

时间:2017-05-23 10:26:45

标签: python python-2.7 button tkinter wait

本学期我参加了一个网络编程课,我的项目包含一个测验游戏,带有简单的图形界面。

我想显示问题,就像玩家点击按钮回答一样。

问题是,我不知道如何在"wait for click"中对python进行编码,代码正在执行直到结束。

我尝试使用boolean条件的一段时间(如果没有点击然后等待),这就像我想要的那样等待,但是没有显示图形界面......

这是我的代码,我有点绝望

感谢您的帮助。

import numpy as np
from numpy.random import shuffle
from random import randint
import socket
import time
from Tkinter import *
from time import clock


class Interface(Frame):
    def __init__(self, fenetre, **kwargs):
        Frame.__init__(self, fenetre, width=768, height=576, **kwargs)
        self.pack(fill=BOTH)


        #DATAS
        self.question = ["What is the capital of France?","In which continent is Argentina?","Where is Big Ben?","What is the most densely populated country?","What language do they speak in Brazil?"]
        self.answer = [["Paris","London","Berlin","Madrid"],["South America","Africa","Europe","Asia"],["London","New York","Mexico","Jakarta"],["China","India","USA","Indonesia"],["Portuguese","Spanish","French","English"]]

        self.question_done=[0]*(len(self.question))
        #SCORE, stored as a list score[0]--> score of the player 1
        self.score=[0]


        # Creation of widgets
        self.message = Label(self, text="Welcome to the Bule Game")
        self.message.pack()

        self.bouton_quitter = Button(self, text="Quitter", command=self.quit)
        self.bouton_quitter.pack(side="bottom")


        #Total number of questions
        self.totalnb = 3


        self.bouton_a1 = Button(self, text="",command = self.checkAnswer)
        self.bouton_a1.pack(side="left")
        self.bouton_a2 = Button(self, text="",command = self.checkAnswer)
        self.bouton_a2.pack(side="left")
        self.bouton_a3 = Button(self, text="",command = self.checkAnswer)
        self.bouton_a3.pack(side="left")
        self.bouton_a4 = Button(self, text="",command = self.checkAnswer)
        self.bouton_a4.pack(side="left")




        for i in range(self.totalnb):
            #Choose the question
            self.nbq = self.chooseQuestion(self.question)
            print("the number is {}".format(self.nbq))
            self.message["text"] = self.question[self.nbq]            
            #answers possible
            self.ans=self.displayA(self.question,self.answer,self.nbq)            
            self.play()



    def play(self):
            #update buttons
            self.bouton_a1["text"]=self.ans[0]
            self.bouton_a1["command"]=(lambda: self.checkAnswer(self.answer,self.ans[0],self.nbq,self.score))

            self.bouton_a2["text"]=self.ans[1]
            self.bouton_a2["command"]=(lambda: self.checkAnswer(self.answer,self.ans[1],self.nbq,self.score))

            self.bouton_a3["text"]=self.ans[2]
            self.bouton_a3["command"]=(lambda: self.checkAnswer(self.answer,self.ans[2],self.nbq,self.score))

            self.bouton_a4["text"]=self.ans[3]
            self.bouton_a4["command"]=(lambda: self.checkAnswer(self.answer,self.ans[3],self.nbq,self.score))





    #CHOOSE RANDOMLY A QUESTION IN THE LIST
    def chooseQuestion(self,question):
        k = randint(0,len(question)-1)
        if (self.question_done[k]!=0):
            while(self.question_done[k]!=0):
                k = randint(0,len(question)-1)
            self.question_done[k]=1
        else :
            self.question_done[k]=1
        #print(question[k])
        #displayA(question,answer,k)
        #print("le num interne est {} ".format(k))
        return k


    #SHOW THE POSSIBLE ANSWERS
    def displayA(self,question,answer,i):
        a = answer[i]
        order = np.arange(4)
        shuffle(order) #create list from 1 to 4 in different order --> to print the answers in random order
        a_display = [a[order[0]],a[order[1]],a[order[2]],a[order[3]]]
        return a_display

    #CHECK IF GOOD ANSWER OR NOT
    def checkAnswer(self,answer,agiven,qnb,score):
        print("CHECK")

        test = False
        if(answer[qnb][0] in agiven):
            test = True
            score[0]=score[0]+1
        print("the answer is {}".format(test))
        return test

    def quit(self):
        self.message["text"] = "The score is {}.".format(self.score)




fenetre = Tk()
interface = Interface(fenetre)
interface.mainloop()

1 个答案:

答案 0 :(得分:1)

如果您希望程序等待按钮单击,那么您应该在按钮回调命令中执行下一个要执行的代码。我将问题代码转移到名为nextQuestion的方法中,该方法在条件满足后在checkAnswer中调用。我还做了一些小的改进,有足够的评论来解释它们(我认为)。

以下是完整的代码:

import numpy as np
from numpy.random import shuffle
from random import randint
import socket
import time
from Tkinter import *
from time import clock


class Interface(Frame):
    def __init__(self, fenetre, **kwargs):
        Frame.__init__(self, fenetre, width=768, height=576, **kwargs)
        self.pack(fill=BOTH)

        #DATAS
        self.question = ["What is the capital of France?","In which continent is Argentina?","Where is Big Ben?","What is the most densely populated country?","What language do they speak in Brazil?"]
        self.answer = [["Paris","London","Berlin","Madrid"],["South America","Africa","Europe","Asia"],["London","New York","Mexico","Jakarta"],["China","India","USA","Indonesia"],["Portuguese","Spanish","French","English"]]

        self.question_done=[0]*(len(self.question))
        #SCORE, stored as a list score[0]--> score of the player 1
        self.score=[0]

        # Creation of widgets
        self.message = Label(self, text="Welcome to the Bule Game")
        self.message.pack()

        self.bouton_quitter = Button(self, text="Quitter", command=self.quit)
        self.bouton_quitter.pack(side="bottom")

        self.bouton_start = Button(self, text="Start", command=self.startQestion)
        self.bouton_start.pack()


        #Total number of questions
        self.totalnb = 3

        # Variable to keep track of how many questions have been asked
        self.questions_asked = 1 


    def startQestion(self):
        # Create buttons before you ask the first questions
        self.bouton_a1 = Button(self, text="   ",command = self.checkAnswer)
        self.bouton_a1.pack(side="left")
        self.bouton_a2 = Button(self, text="   ",command = self.checkAnswer)
        self.bouton_a2.pack(side="left")
        self.bouton_a3 = Button(self, text="   ",command = self.checkAnswer)
        self.bouton_a3.pack(side="left")
        self.bouton_a4 = Button(self, text="   ",command = self.checkAnswer)
        self.bouton_a4.pack(side="left")

        self.bouton_start.pack_forget() #Remove the start button
        self.nextQuestion() # ask question


    def nextQuestion(self):
        #Choose the question
        self.nbq = self.chooseQuestion(self.question)
        print("the number is {}".format(self.nbq))
        self.message["text"] = self.question[self.nbq]            
        #answers possible
        self.ans=self.displayA(self.question,self.answer,self.nbq)     
        self.play()


    def play(self):
            #update buttons
            self.bouton_a1["text"]=self.ans[0]
            self.bouton_a1["command"]=(lambda: self.checkAnswer(self.answer,self.ans[0],self.nbq,self.score))

            self.bouton_a2["text"]=self.ans[1]
            self.bouton_a2["command"]=(lambda: self.checkAnswer(self.answer,self.ans[1],self.nbq,self.score))

            self.bouton_a3["text"]=self.ans[2]
            self.bouton_a3["command"]=(lambda: self.checkAnswer(self.answer,self.ans[2],self.nbq,self.score))

            self.bouton_a4["text"]=self.ans[3]
            self.bouton_a4["command"]=(lambda: self.checkAnswer(self.answer,self.ans[3],self.nbq,self.score))



    #CHOOSE RANDOMLY A QUESTION IN THE LIST
    def chooseQuestion(self,question):
        k = randint(0,len(question)-1)
        if (self.question_done[k]!=0):
            while(self.question_done[k]!=0):
                k = randint(0,len(question)-1)
            self.question_done[k]=1
        else :
            self.question_done[k]=1
        #print(question[k])
        #displayA(question,answer,k)
        #print("le num interne est {} ".format(k))
        return k


    #SHOW THE POSSIBLE ANSWERS
    def displayA(self,question,answer,i):
        a = answer[i]
        order = np.arange(4)
        shuffle(order) #create list from 1 to 4 in different order --> to print the answers in random order
        a_display = [a[order[0]],a[order[1]],a[order[2]],a[order[3]]]
        return a_display

    #CHECK IF GOOD ANSWER OR NOT
    def checkAnswer(self,answer,agiven,qnb,score):
        print("CHECK")

        test = False
        if(answer[qnb][0] in agiven):
            test = True
            score[0]=score[0]+1
        print("the answer is {}".format(test))
        #Check to see if the maximum number of questions has been asked already
        if self.questions_asked < self.totalnb:
            self.nextQuestion() # Ask the next question if less number of questions has been asked
            self.questions_asked += 1  # Update the number of questions that has been asked

        # If maximum number of questions is asked, display end message and remove answer buttons
        else:
            self.message["text"] = "End of Qestion"
            self.bouton_a1.pack_forget()
            self.bouton_a2.pack_forget()
            self.bouton_a3.pack_forget()
            self.bouton_a4.pack_forget()
        #return test

    def quit(self):
        self.message["text"] = "The score is {}.".format(self.score)



fenetre = Tk()
interface = Interface(fenetre)
interface.mainloop()