我正在嘗試使用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