vincentlai
vincentlai

Reputation: 429

How to close other window by python Tkinter?

I have following python code in Tkinter.

import tkinter as tk


def main_gui(login, s):
    login.quit()  # close login window

    win = tk.Tk()
    win.geometry('300x150') 

    name = tk.Label(win, text='Hello' + s.get())  # Hello David
    name.pack()
    win.mainloop()

# initial Tkinter frame
login = tk.Tk()
login.title('Login')
login.geometry('300x150')

# input user name
user_name_var = tk.StringVar()
user_name_var.set('David')
tk.Label(login, text='User name').place(x=10, y=50)
user_name = tk.Entry(login, textvariable=user_name_var)
user_name.place(x=100, y=50)

input_ok = tk.Button(win_login, command=lambda: main_gui(login, user_name), text='OK', width=15)
input_ok.place(x=100, y=90)

win_login.mainloop()

I want to close login window, but my code can not close it. How to solve it.

Upvotes: 0

Views: 971

Answers (2)

dkelaty
dkelaty

Reputation: 5

you can use the

root.withdraw()

function, this will close the window without completely destroying all of the root.after functions

Upvotes: 0

Hans
Hans

Reputation: 2625

You are almost there - only two details you have to adapt:

  1. The method to remove a widget in Tkinter is destroy, so login.quit() should be login.destroy().
  2. Once login is destroyed, the user_name Entry will also be destroyed, and you will not be able to get the name from it anymore. You should get the name earlier, e.g., directly in the lambda:

    ... lambda: main_gui(login, user_name.get()), ...

Upvotes: 2

Related Questions