Python 标签未更新

Python 标签未更新,python,tkinter,python-3.5,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 t

我正在尝试使用
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
基本上,当按下“下一个问题”时,问题标签不会更新。再次按下“下一个问题”将使代码陷入一个错误循环


老实说,我看不出哪里出了问题,但这可能是因为我缺乏经验。首先,简短的回答是,您实际上没有更新
StringVar
问题打印的内容。我将通过将
reloadGUI()
函数更改为:

def reloadGUI():
    global questNum
    questNum = generateAndCheck()
    showQuestion()
    answer.set("")  # Clear the answer for the new question
此外,正如Dzhao所指出的,在没有问题之后出现错误的原因是,您需要在
generateAndCheck()
函数中设置某种保护,以防止无限递归


此外,我建议你改变你决定要问什么问题的方式,因为你现在的提问方式是不必要的复杂。进一步查看模块,尤其是函数。您会注意到,当列表为空时,它会引发一个
索引器
,因此您可以捕获该错误,这将有助于解决Dzhao指出的问题。

RobertR回答了您的第一个问题。再次按下
Next Question
按钮时收到错误的原因是列表中的
b3
有两个数字,0和1。因此,当您运行该函数两次时,您将从该列表中删除1和0。然后你有一个空的列表。当您第三次调用
reloadGUI
时,您将永远不会点击
else
语句,因为生成的
randint
将永远不会在
b3可能性中。调用了
if
子句,然后进入了一个无结尾的递归调用

解决此问题的一个方法可能是在
常规和check
函数中进行检查:

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

调用
reloadGUI()
时,实际上没有更新
StringVar
questionToPrint
的内容。我该怎么做?第二次按“下一个问题”后收到的错误是,数字列表中没有任何内容。因此,函数
reloadGUI
将一直运行,直到达到Python的递归极限。我们能不能放松一下反对票和接近票?这会产生和以前一样的效果-问题标签不会改变,错误循环也会发生