0

I'm working on functions within a class, and one of the issues I'm running into is adding a button that terminates the program. Here is the current code:

class ClassName():
    def __init__(self, root):
        self.root = root

    def close_root(self, root):
        root.destroy()
        root.quit()

    def addExitButton(self, root):
        Button(root, text = 'Exit', width = 10, command = self.close_root).grid(row = 5, 
             column = 0)

Within the button arguments, I have tried command = self.close_root(root) But this gives me an error because you can't call a function if you want the button to do something (I forget the reason as to why this is). I have also tried

def close_root(self):
    self.destroy()
    self.quit()

def addExitButton(self, root):
    Button(..., command = self.close_root,...)

And this does not work either as the class doesn't have the attribute destroy. I'm not sure how to approach this after trying a few different ways.

itsdarrylnorris
  • 630
  • 5
  • 21
Brandon Molyneaux
  • 1,543
  • 2
  • 12
  • 23

1 Answers1

0

You need to actually access the root's functions. So using self.root.destory() or self.root.quit() will work because your root object has those methods but your class does not.

You should also only use one of them, in this case, destroy is the best option I think. And you can probably just use that when creating the button. So replace the button callback (command) with self.root.destory.

More here on how to close a Tkinter window here.

Preston Hager
  • 1,514
  • 18
  • 33
  • I ended up using one of the answers in the link that was provided: `command = lambda root=root:self.close_root(root)`. This allowed me to keep the original function `close_root()`. Thanks! – Brandon Molyneaux May 22 '18 at 01:11