How would I make destroy() method in tkinter work with my code?

血红的双手。 提交于 2020-01-12 18:59:48

问题


from tkinter import *

class GameBoard(Frame):
  def __init__(self):
    Frame.__init__(self)
    self.master.title("test")
    self.grid()
    #button frame
    self.__buttonPane = Frame(self)
    self.__buttonPane.grid()
    #buttons
    self.__buttonA1 = Button(self.__buttonPane,text = "A1",command = self._close)
    self.__buttonA1.grid()

  def _close(self):
    GameBoard().destroy()


def main():
  GameBoard().mainloop()

main()

How would I make my function for close to work?


回答1:


GameBoard()

creates a new instance of GameBoard. Therefore:

GameBoard().destroy()

creates a new instance and calls destroy() on it which has no effect on the existing instance.

You want access the current instance in your _close() method which is done through self:

def _close(self):
    self.destroy()

However, this only destroys the frame (and its child windows, like the button), not the top level window (master).

To completely close the UI, you could call self.master.destroy() or simply self.quit():

def _close(self):
    self.quit()



回答2:


self.master.destroy() will close both the parent and child process (see I.E. for example). self.destroy will close the child process. I know this is an old post, but I figured this information might still be applicable to someone.

I.E.

def _close(self):
    self.master.destroy()


来源:https://stackoverflow.com/questions/13650617/how-would-i-make-destroy-method-in-tkinter-work-with-my-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!