我正在尝试使用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”时,问题标签不会更新。再次按下“下一个问题”会将代码放入一个错误循环中。
老实说,我不能看到我要去哪里错了,但是这可能是由于我缺乏经验
你不是实际更新''StringVar'的questionToPrint'内容,当你调用'reloadGUI()'。 – RobertR
我该怎么做? –
第二次按下一个问题后收到的错误是数字列表中没有任何内容。因此,你的函数'reloadGUI'将继续运行,直到你达到Python的递归限制。 – Dzhao