2016-03-30 139 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?