Andrew Valdez
Andrew Valdez

Reputation: 75

How to close top level tkinter window with a button, if button in the window already is bound to a function

I'm somewhat new to tkinter and Python and am working on a semester long project. Basically I have a main tkinter window, then from that window, topLevel windows are called depending on the user input. In the each topLevel window I have a button that performs a function, I also want this button to close the topLevel window after performing that function. What would be the best way to approach this problem?

I have tried to destroy or close the window, but it ends up closing the main window also. I am just looking for a way to close the topLevel window and perform the function with the click of a button

class MainWindow:
        # Entry box
        self.entry = StringVar()
        self.text_box = Entry(master, textvariable=self.entry)
        self.text_box.grid(row=1, column=2)

        # Displays and binds button, so when clicked, the enter_button function is called
        self.input_button = Button(master, text='Enter', command=self.enter_button)
        self.input_button.grid(row=1, column=3, sticky='W')


    def enter_button(self):
        # Get user input and perform the given command
        command = self.entry.get()

        # Creates a root for a toplevel window
        top = Toplevel()

        if command == '1':
            add_gui = AddPayment(top)
            top.mainloop()
        elif command == '2':
        #rest of classes/commands

main

def main():
    root = Tk()
    app = MainWindow(root)
    root.mainloop()


if __name__ == '__main__':
    main()

AddPayment class

class AddPayment:
    def __init__(self,master):
        self.master = master
        self.add_label = Label(master, text='How much is the payment for?')

        # payment box
        self.pay = StringVar()
        self.pay_box = Entry(master, textvariable=self.pay)
        self.add_button = Button(master, text='Add', command=self.add_payment)

        # position widgets
        self.pay_box.grid(row=1, column=2)
        self.add_label.grid(row=1, column=1)
        self.add_button.grid(row=1, column=3)

    def add_payment(self):
        database.add_pay(self.pay.get())

In this example I would like something in the add_payment function to close the topLevel window after the add_pay function is performed somehow. Thanks in advance

Upvotes: 2

Views: 642

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385900

You have a couple problems. For one, you should never call mainloop more than once. You need to remove the call to mainloop() from the enter_button function.

The other problem is that you're not saving a reference to the toplevel, so you've made it more-or-less impossible to destroy it. You simply need to save a reference and then call destroy on the reference.

self.top = Toplevel()
...
self.top.destroy()

Upvotes: 2

Related Questions