2016-03-30 137 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 

基本上,按「Next Question」時,問題標籤不會更新。再次按下「下一個問題」會將代碼放入一個錯誤循環中。

老實說,我不能看到我要去哪裏錯了,但是這可能是由於我缺乏經驗

+0

你不是實際更新''StringVar'的questionToPrint'內容,當你調用'reloadGUI()'。 – RobertR

+0

我該怎麼做? –

+1

第二次按下一個問題後收到的錯誤是數字列表中沒有任何內容。因此,你的函數'reloadGUI'將繼續運行,直到你達到Python的遞歸限制。 – Dzhao

回答

0

首先,簡單的答案是,你沒有真正更新的StringVarquestionToPrint內容。我會通過改變reloadGUI()功能,此解決這個問題:

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

此外,作爲Dzhao指出的那樣,你跑出來的問題後,你得到一個錯誤的原因是因爲你需要把某種保護在你的generateAndCheck()函數內防止無限遞歸。

此外,我建議你改變你確定要問什麼問題的方式,因爲你現在擁有它的方式是不必要的複雜。多看一下random模塊,特別是random.choice()函數。當列表爲空時,您會注意到它會產生一個IndexError,所以您可以捕獲該錯誤,這將有助於解決Dzhao指出的問題。

+0

這會產生與以前相同的效果 - 問題標籤不會更改,並且發生錯誤循環 –

0

RobertR回答了你的第一個問題。當您再次按下Next Question按鈕時,您收到錯誤的原因是因爲您的列表B3Possibilities有兩個數字0和1.因此,當您運行該功能兩次時,您將從此列表中刪除一個和零。然後你有一個空的列表。當您第三次致電reloadGUI時,您將永遠無法擊中您的else聲明,因爲生成的randint永遠不會處於B3Possibilites。你的if條款被調用,你潛入一個無休止的遞歸調用。

對此的解決方案可能是在你的generageAndCheck功能檢查:

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