计时器线程和TKINTER的麻烦



我正在做我的第一个大项目,即测验。我坚持尝试限制用户必须回答问题的时间。我已经搜索了,似乎有效的唯一选择是使用计时器线程。我根本不熟悉线程或任何略有高级的TKINTER,所以我全都耳朵。

def revisionMode(question):
    inputAnswer = StringVar()
    #-----Creation & placement of buttons and labels
    qLabel = Label(screen1, text = question.prompt[0]
    qLabel.grid(row = 6, column = 2)
    answerBox = Entry(screen1, textvariable = inputAnswer)
    answerBox.grid(column = 2, row = 10)
    t = Timer(7.0, nextQuestion, args=(False, question.difficulty), kwargs=None)
    t.start()
    #-----The button that will trigger the validation of the answer
    Button(screen1, text = "Submit", command = lambda: checkAnswer(question)).grid(column = 3, row = 9)

我从中获得的错误是:

RuntimeError:主线程不在主循环中。

从我的理解和谷歌搜索,tkinter和螺纹效果不佳,我已经看到了使用队列的解决方案。

您不需要计时器线程来简单。tkinter小部件具有名为after的方法,将来可以用于运行命令。

例如,要在7秒后致电nextQuestion,您将执行此操作:

screen1.after(7000, nextQuestion, False, question.difficulty)

如果要取消计时器,保存返回值并将其在呼叫after_cancel中使用:

after_id = screen1.after(7000, nextQuestion, False, question.difficulty)
...
screen1.after_cancel(after_id)

最新更新