标签未更新

时间:2016-03-30 18:07:41

标签: python tkinter python-3.5

我正在尝试使用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

基本上,当按下“下一个问题”时,问题标签不会更新。再次按“下一个问题”会将代码抛入一个很好的错误循环中。

老实说,我看不出我出错的地方,但这可能是由于我缺乏经验

2 个答案:

答案 0 :(得分:0)

首先,简短的回答是您实际上并未更新StringVar questionToPrint的内容。我会通过将reloadGUI()函数更改为此来解决此问题:

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

另外,正如Dzhao所指出的那样,在你用完问题后出现错误的原因是因为你需要在generateAndCheck()函数中加入某种保护来防止无限递归。

此外,我建议您更改确定要问的问题的方式,因为您现在拥有它的方式不必要地复杂化。再看一下random模块,尤其是random.choice()函数。当列表为空时,你会注意到它会引发一个IndexError,这样你就可以发现这个错误,这将有助于解决Dzhao指出的问题。

答案 1 :(得分:0)

RobertR回答了你的第一个问题。再次按下Next Question按钮时收到错误的原因是因为您的列表B3Possibilities有两个数字,0和1.所以当您运行该函数两次时,您将删除一个和这个列表中的零。然后你有一个空列表。当您第三次致电reloadGUI时,您永远不会点击else语句,因为生成的randint将永远不会出现在B3Possibilites中。你的if子句被调用,你潜入一个无止境的递归调用。

解决此问题的方法可能是检查generageAndCheck功能:

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