2016-03-30 26 views
0

tkinterを使用してGUIを作成しようとしています。 「次の質問」を押すとラベルが更新されない

from tkinter import * 
from random import randint 

B3Questions = ["How is a cactus adapted to a desert environment?", "What factors could cause a species to become extinct?"] 
B3Answers = ["It has leaves reduced to spines to cut water loss, a thick outer layer to cut down water loss and a deep-wide spreading root system to obtain as much water as possible", "Increased competition, new predators and new diseases"] 
B3Possibles = [x for x in range (len(B3Questions))] 

def loadGUI(): 

    root = Tk() #Blank Window 

    questNum = generateAndCheck() 
    questionToPrint = StringVar() 
    answer = StringVar() 

    def showQuestion(): 

     questionToPrint.set(B3Questions[questNum]) 

    def showAnswer(): 

     answer.set(B3Answers[questNum]) 

    def reloadGUI(): 

     global questNum 
     questNum = generateAndCheck() 
     return questNum 

    question = Label(root, textvariable = questionToPrint) 
    question.pack() 

    answerLabel = Label(root, textvariable = answer, wraplength = 400) 
    answerLabel.pack() 

    bottomFrame = Frame(root) 
    bottomFrame.pack() 
    revealAnswer = Button(bottomFrame, text="Reveal Answer", command=showAnswer) 
    revealAnswer.pack(side=LEFT) 
    nextQuestion = Button(bottomFrame, text="Next Question", command=reloadGUI) 
    nextQuestion.pack(side=LEFT) 

    showQuestion() 
    root.mainloop() 

def generateAndCheck(): 

    questNum = randint(0, 1) 
    print(questNum) 

    if questNum not in B3Possibles: 
     generateAndCheck() 
    else: 
     B3Possibles.remove(questNum) 
     return questNum 

基本的には、質問のラベルが更新されません:これは私のコードです。 「次の質問」をもう一度押すと、コードがエラーの素晴らしいループに投げ込まれます。

私が間違っているつもりだところ、私は正直に見ることができないが、それが原因経験

+0

'reloadGUI()'。 – RobertR

+0

どうすればいいですか? –

+1

次の質問を2回押した後に表示されるエラーは、数字のリストに何もないことです。したがって、あなたの関数 'reloadGUI'はPythonの再帰的制限に達するまで動作し続けます。 – Dzhao

答えて

0

まずオフの私の不足のために可能性があります、短い答えは、あなたが実際にStringVarquestionToPrintの内容を更新していないということです。私はこれにreloadGUI()機能を変更することで、この問題を解決します:Dzhaoが指摘したように、あなたが保護のいくつかの並べ替えを配置する必要があるため

def reloadGUI(): 
    global questNum 
    questNum = generateAndCheck() 
    showQuestion() 
    answer.set("") # Clear the answer for the new question 

はまた、あなたが質問を使い果たした後、あなたがエラーを取得している理由は、あなたのgenerateAndCheck()関数内で、無限再帰を防ぎます。

さらに、私はあなたが今質問している方法を不必要に複雑にしているため、質問する方法を変更することをお勧めします。 randomモジュールをもう少し調べてください。特にrandom.choice()という機能があります。 Dzhaoが指摘していた問題を解決するのに役立ちますので、リストが空のときにはIndexErrorが発生します。

+0

これは前と同じ結果になります。質問ラベルは変更されず、エラーのループが発生します –

0

RobertRがあなたの最初の質問に答えました。 Next Questionボタンを再度押したときにエラーが発生する理由は、リストB3Possibilitiesに2つの数字、0と1があるためです。したがって、関数を2回実行すると、このリストから1とゼロの両方が削除されます。次に空のリストがあります。 reloadGUIに3回目に電話すると、elseという文が表示されることはありません。randintは、決してB3Possibilitesになることはありません。 if句が呼び出され、終了しない再帰呼び出しが行われます。

これに対する解決策は、あなたのgenerageAndCheck機能にチェックを持っているかもしれません:あなたが呼び出すときは、実際に `` StringVar` questionToPrint`の内容を更新していない

if(len(B3Possibiles) == 0): 
    #run some code. Maybe restart the program?