Tkinter 按钮在某些情况下不会破坏标签

Tkinter button not destroying labels under certain conditions

有点长见谅

基本上,主要问题是 'add_button3'(返回主页按钮)不起作用,如果您之前按 'add_button2'(新问题),它将带您到主页但没有'销毁任何标签。然而,如果您提交了一个问题并且标记仍然可见,然后按 'add_button3' 它会破坏所有标签并毫无问题地显示主页。缩进或任何导致此问题的问题?我在下面附上了一段相关代码,但整个项目可以在 https://github.com/wright-jake/math-game

找到

感谢任何能帮助我的人!

def addition():

  #select random numbers
  num_1 = randint(0,30)
  num_2 = randint(0,30)

  #displays question
  add_label1 = Label(root, text=f"What is {num_1} + {num_2} ?\n",font=('Times_New_Roman',16))
  add_label1.place(height=30,x=190,y=75)

  #provide answer in entry box
  add_selection = Entry(root)
  add_selection.place(height=30,x=190,y=120)

  #accept answer and decide if it is right or wrong
  def add_submt():

    #correct
    if int(add_selection.get()) == num_1 + num_2:
      mark = Label(root,text="Correct! Keep on playing!\n",font=('Times_New_Roman',16))
      mark.place(height=30,x=160,y=200)

    #incorrect
    else:
      mark = Label(root,text=f"Incorrect, the answer is {num_1+num_2}.\n",font=('Times_New_Roman',16))
      mark.place(height=30,x=150,y=200)

    #new question will destroy old question and loop the addition function again
    def new_question():
      addition()
      mark.destroy()

    #back to homepage destroys current page
    def add_back():
      add_label1.destroy()
      add_button1.destroy()
      add_button2.destroy()
      add_selection.destroy()
      add_button3.destroy()
      mark.destroy()
      homepage()

    #new question button
    add_button2 = Button(root,text="New Question",command=new_question)
    add_button2.place(height=30,x=190,y=240)

    #back to homepage button
    add_button3 = Button(root,text="Back",command=add_back)
    add_button3.place(height=30,x=340,y=240)

  #submit answer
  add_button1 = Button(root,text="Submit",command=add_submt)
  add_button1.place(height=30,x=190,y=160)

我建议你做的是为你的页面构建框架,这样你就可以将每个按钮添加到你的框架中,如果你想从问题页面跳转,你只需做例如(question_frame.destroy()) 并且此框架中的所有按钮和标签将被销毁,您可以调用您的主页功能。然后你只需在另一个框架中设置你的主页等等...

示例:

homepage_frame = Frame(root)

homepage_frame.pack()

l1 = label(homepage_frame...)
l1.pack()

只要把它放在一个函数中,然后为你所有的“windows”重复它。