How to Close a Tkinter Window by Pressing a Button

How can I close this tkinter window after pressing the OK button?

I think you have to include master.destroy() after printing:

from tkinter import *

OPTIONS = [
"Physician 1",
"Physician 2",
"Physician 3"
]

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

def ok():
physician_name=variable.get()
print (physician_name)
master.destroy()

button = Button(master, text="OK", command=ok)
button.pack()

mainloop()

How do I close a Tkinter Window when a new Tkinter window opens?

Create empty window and run mainloop() (event loop) to keep it open

import tkinter as tk

window = tk.Tk()
window.mainloop()

To close it you can use standard button [x] on title bar.

Or you would need to put button in window which runs window.destroy() to close it.

import tkinter as tk

window = tk.Tk()

button = tk.Button(window, text='CLOSE', command=window.destroy)
button.pack()

window.mainloop()

BTW: in command= it has to be window.destroy without (). It is "callback" - name of function which will be executed when you press button.


In this example button runs function which closes first window and create second window.

import tkinter as tk

# --- functions ---

def second_window():
window.destroy()

second = tk.Tk()

button = tk.Button(second, text='CLOSE SECOND', command=second.destroy)
button.pack()

second.mainloop()

# --- main ---

window = tk.Tk()

button = tk.Button(window, text='CLOSE FIRST', command=second_window)
button.pack()

window.mainloop()

Previous version opens second window only if you use tk.Button() but it doesn't do it when you press [x]. You need

window.protocol("WM_DELETE_WINDOW", second_window)

to run second_window when you press [x]

import tkinter as tk

# --- functions ---

def second_window():
window.destroy()

second = tk.Tk()

button = tk.Button(second, text='CLOSE SECOND', command=second.destroy)
button.pack()

second.mainloop()

# --- main ---

window = tk.Tk()

button = tk.Button(window, text='CLOSE FIRST', command=second_window)
button.pack()

window.protocol("WM_DELETE_WINDOW", second_window)

window.mainloop()

You can even run code which close and create again the same window

import tkinter as tk

# --- functions ---

def first_window():
global window

if window:
window.destroy()
#window = None

window = tk.Tk()

button = tk.Button(window, text='CLOSE FIRST', command=first_window)
button.pack()

window.protocol("WM_DELETE_WINDOW", first_window)

window.mainloop()

# --- main ---

window = None
first_window()

In this example I use window = None to check if window exists and close it. You can use this method to close first window when you create new window.


In this example I use first_window = None and second_window = None so I can check if other window is open and close it.

import tkinter as tk

# --- functions ---

def open_second_window():
global first_window
global second_window

if first_window:
first_window.destroy()
first_window = None

second_window = tk.Tk()

button = tk.Button(second_window, text='OPEN FIRST', command=open_first_window)
button.pack()

second_window.protocol("WM_DELETE_WINDOW", open_first_window)

second_window.mainloop()

def open_first_window():
global first_window
global second_window

if second_window:
second_window.destroy()
second_window = None

first_window = tk.Tk()

button = tk.Button(first_window, text='OPEN SECOND', command=open_second_window)
button.pack()

first_window.protocol("WM_DELETE_WINDOW", open_second_window)

first_window.mainloop()

# --- main ---

first_window = None
second_window = None
open_first_window()

But I don't know why you what to close one window and open another. You can hide first window if later you want to go back to first window. Or you can keep widgets in Frame() and remove/this frame to show other frame.

Python - Tkinter how to close window after button is pressed?

this will work with the login button,,,, i sent the window with the login function

here i added the window to the function

def login(usernameLogin, passwordLogin,btn):

.
here in the "btn.destroy()" i closed the window

if results:#Validates if the username/password is recognised
for i in results:
messagebox.showinfo("", "Welcome "+i[1]+"!")
btn.destroy()
QuestionMenu()

.
here i sent the window to the function.

btn = ttk.Button(window, text="Log in", command=lambda: login(usernameLogin, passwordLogin,window))

.

import sqlite3
from tkinter import ttk
import tkinter
from tkinter import messagebox

#SQL DATABASES~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def SQLQuestion():
with sqlite3.connect("games.db") as db:
cursor = db.cursor()

cursor.execute("""CREATE TABLE IF NOT EXISTS game (
questionID integer PRIMARY KEY AUTOINCREMENT,
question text,
answer text
)""")

def SQLUser():
with sqlite3.connect("User.db") as db:
cursor = db.cursor()

cursor.execute("""CREATE TABLE IF NOT EXISTS user (
userID INTEGER PRIMARY KEY,
username VARCHAR(20) NOT NULL,
password VARCHAR(20) NOT NULL,
userscore INTEGER,
usertime REAL
)""")

#SQL USER LOG IN/CREATE/DELETE ACCOUNT~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def login(usernameLogin, passwordLogin,btn):
while True:
username = usernameLogin.get()#Asks for username
password = passwordLogin.get()#Asks for password
with sqlite3.connect("User.db") as db:#Creates a connection to database
c = db.cursor()
find_user = ("SELECT * FROM user WHERE username = ? AND password = ?")#Validates inputs for account
c.execute(find_user,[(username),(password)])
results = c.fetchall()#Fetches values from database

if results:#Validates if the username/password is recognised
for i in results:
messagebox.showinfo("", "Welcome "+i[1]+"!")
btn.destroy()
QuestionMenu()
break

else:
messagebox.showinfo("", "Password and username is not recognised")
break
window.destroy()

def newUser(username1, password1):
found = 0
while found == 0:
username = username1.get()
with sqlite3.connect("User.db") as db:
c = db.cursor()
findUser = ("SELECT * FROM user WHERE username = ?")
c.execute(findUser, [(username)])#Checks existence of username in database

if c.fetchall():
messagebox.showinfo("Username", "Username taken please try again.")
break
else:
messagebox.showinfo("", "Account has been created!")
found = 1

password = password1.get()
insertData = '''INSERT INTO user(username, password)
VALUES(?,?)'''#Inserts new account into databse
c.execute(insertData, [(username),(password)])
db.commit()

def newUserTkinter():
window = tkinter.Tk()
window.title("Create new account")

labelOne = ttk.Label(window, text = "Enter a username:")
labelOne.grid(row = 0, column = 0)
username1 = tkinter.StringVar(window)#value type is classified as a string
usernameEntry = ttk.Entry(window, width = 30, textvariable = username1)
usernameEntry.grid(row = 1, column = 0)

labelTwo = ttk.Label(window, text = "Enter a password:")
labelTwo.grid(row = 2, column = 0)
password1 = tkinter.StringVar(window)#value type is classified as a string
passwordEntry = ttk.Entry(window, width = 30, textvariable = password1)
passwordEntry.grid(row = 3, column = 0)

btn = ttk.Button(window, text="Submit", command=lambda: newUser(username1, password1))
btn.grid(row = 3, column = 1)

def removeUser(usernameD, passwordD):
exists = 0
while exists == 0:#Validates exsistence of account username
username = usernameD.get()
password = passwordD.get()
with sqlite3.connect("User.db") as db:
c = db.cursor()
findUser = ("SELECT * FROM user WHERE username = ?")
c.execute(findUser, [(username)])

if c.fetchall():
messagebox.showinfo("Delete account", "Account deleted!")
exists = 1
else:
messagebox.showinfo("", "Account does not exist")
break

remove_user = ("DELETE from user WHERE username = ? AND password = ?")
c.execute(remove_user,[(username),(password)])
db.commit()

def removeUserTkinter():
window = tkinter.Tk()
window.title("Delete account")

labelOne = ttk.Label(window, text = "Enter account username:")
labelOne.grid(row = 0, column = 0)
usernameD = tkinter.StringVar(window)#value type is classified as a string
usernameEntry = ttk.Entry(window, width = 30, textvariable = usernameD)
usernameEntry.grid(row = 1, column = 0)

labelTwo = ttk.Label(window, text = "Enter account password:")
labelTwo.grid(row = 2, column = 0)
passwordD = tkinter.StringVar(window)#value type is classified as a string
passwordEntry = ttk.Entry(window, width = 30, textvariable = passwordD)
passwordEntry.grid(row = 3, column = 0)

btn = ttk.Button(window, text="Submit", command=lambda: removeUser(usernameD, passwordD))
btn.grid(row = 3, column = 1)

def menu():
with sqlite3.connect("User.db") as db:
c = db.cursor()
c.execute("SELECT * FROM user")
print(c.fetchall())

window = tkinter.Tk()
window.title("Treasure Hunt Game!")

labelOne = ttk.Label(window, text = """ ~~~~~~~~~~~~~ USER MENU ~~~~~~~~~~~~~
""")#label displays instruction
labelOne.grid(row = 0, column = 0)#places label in a grid

btn = ttk.Button(window, text = "Create account", command = newUserTkinter)
btn.grid(row = 1, column = 0)#places button in a grid

btn = ttk.Button(window, text = "Delete account", command = removeUserTkinter)
btn.grid(row = 2, column = 0)#places button in a grid

labelTwo = ttk.Label(window, text = "Login to your account:")
labelTwo.grid(row = 3, column = 0)

usernameLogin = tkinter.StringVar(window)#value type is classified as a string
usernameEntry = ttk.Entry(window, width = 30, textvariable = usernameLogin)
usernameEntry.grid(row = 5, column = 0)

labelTwo = ttk.Label(window, text = "Username")
labelTwo.grid(row = 4, column = 0)

passwordLogin = tkinter.StringVar(window)#value type is classified as a string
passwordEntry = ttk.Entry(window, width = 30, textvariable = passwordLogin)
passwordEntry.grid(row = 7, column = 0)

labelTwo = ttk.Label(window, text = "Password")
labelTwo.grid(row = 6, column = 0)

btn = ttk.Button(window, text="Log in", command=lambda: login(usernameLogin, passwordLogin,window))
btn.grid(row = 7, column = 1)

#SQL QUESTION ADD/REMOVE/GET~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def insert_question(emp):
conn = sqlite3.connect('games.db')
c = conn.cursor()
c.execute("INSERT INTO game VALUES (?, ?, ?)", (emp))
conn.commit()

def get_question():
conn = sqlite3.connect('games.db')
c = conn.cursor()
c.execute("SELECT * FROM game")
return c.fetchall()

def get_number_total_question(): #Get the total number of question
conn = sqlite3.connect('games.db')
c = conn.cursor()
c.execute("SELECT COUNT(*) FROM game")
return c.fetchone()[0]

def get_single_question(question_number): #Get a question from the database
conn = sqlite3.connect('games.db')
c = conn.cursor()
c.execute("SELECT question FROM game WHERE questionID="+str(question_number))
return c.fetchone()[0]

def get_answer(question_number): #Get the answer from the database
conn = sqlite3.connect('games.db')
c = conn.cursor()
c.execute("SELECT answer FROM game WHERE questionID="+str(question_number))
return c.fetchone()[0]

def remove_question(emp):
conn = sqlite3.connect('games.db')
c = conn.cursor()
c.execute("DELETE from game WHERE question = ?", [emp])
conn.commit()

#Tkinter~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def showInstructions():
messagebox.showinfo("Instructions", """You are a treasure hunter, your goal is to collect atleast 100
gold by the end of the game from treasure chests randomly scattered across the grid.There are 10 chests within a grid and
each treasure chest is worth 10 gold but can only be reclaimed 3 times before it is replaced by a bandit.
Landing on a bandit will cause you to lose all of your
gold and if all the chests have been replaced by bandits and you have less then 100 gold this means you lose!

Press enter to continue...""")#messagebox used for more simple functions (showing messages)

def showLeaderboard():
messagebox.showinfo("Leaderboard", "shows leaderboard")

def con():
messagebox.showinfo("Game", "Time to play!")
window.destroy()

def showQuestions():
emps = get_question()
messagebox.showinfo("List of questions/answers", emps)

def AddQuestion(mathquestion, mathanswer):
mathquestion1 = mathquestion.get()
mathanswer1 = mathanswer.get()
emp_1 = (None, mathquestion1, mathanswer1)
insert_question(emp_1)
messagebox.showinfo("Question inputed!")

emps = get_question()
print(emps)

def removeQuestion(DeleteQuestion):
exists = 0
while exists == 0:#Validates exsistence of question
DeleteQuestion1 = DeleteQuestion.get()
conn = sqlite3.connect('games.db')
c = conn.cursor()
findQuestion = ("SELECT * FROM game WHERE question = ?")
c.execute(findQuestion, [(DeleteQuestion1)])

if c.fetchall():
messagebox.showinfo("Delete qustion","Question deleted!")
exists = 1
else:
messagebox.showinfo("","Question does not exist")
break

remove_question(DeleteQuestion1)

def removeQuestionTk():
window = tkinter.Tk()
window.title("Remove a question.")

labelOne = ttk.Label(window, text = "Enter question to remove:")
labelOne.grid(row = 0, column = 0)
DeleteQuestion = tkinter.StringVar(window)#value type is classified as a string
questionEntry = ttk.Entry(window, width = 30, textvariable = DeleteQuestion)
questionEntry.grid(row = 1, column = 0)

btn = ttk.Button(window, text="Submit", command=lambda: removeQuestion(DeleteQuestion))
btn.grid(row = 1, column = 1)

def QuestionMenu():
with sqlite3.connect("games.db") as db:
c = db.cursor()

window = tkinter.Tk()
window.title("Treasure Hunt Game!")

labelOne = ttk.Label(window, text = """ ~~~~~~~~~~~~~ GAME MENU ~~~~~~~~~~~~~
""")#label displays instruction
labelOne.grid(row = 0, column = 0)#places label in a grid

btn = ttk.Button(window, text = "View instructions", command = showInstructions)
btn.grid(row = 1, column = 0)#places button in a grid

btn = ttk.Button(window, text = "View leaderboard", command = showLeaderboard)
btn.grid(row = 2, column = 0)

btn = ttk.Button(window, text = "View all questions", command = showQuestions)
btn.grid(row = 3, column = 0)

btn = ttk.Button(window, text = "Continue", command = con)
btn.grid(row = 4, column = 0)

labelTwo = ttk.Label(window, text = "Enter a math question:")
labelTwo.grid(row = 5, column = 0)
mathquestion = tkinter.StringVar()#value type is classified as a string
userEntryQ = ttk.Entry(window, width = 30, textvariable = mathquestion)
userEntryQ.grid(row = 6, column = 0)

labelTwo = ttk.Label(window, text = "Enter the answer to this question:")
labelTwo.grid(row = 7, column = 0)
mathanswer = tkinter.StringVar()
userEntryQ = ttk.Entry(window, width = 30, textvariable = mathanswer)
userEntryQ.grid(row = 8, column = 0)

btn = ttk.Button(window, text = "Submit", command=lambda: AddQuestion(mathquestion, mathanswer))
btn.grid(row = 8, column = 1)

btn = ttk.Button(window, text = "Remove a question", command = removeQuestionTk)
btn.grid(row = 9, column = 0)#places button in a grid

SQLUser()
SQLQuestion()
menu()

How to close tkinter window without a button and not closing Python completely?

Without seeing more of the source code, I guess the problem is based on where you call root.destroy()

If it comes after the blocking tk.mainloop(), it will never be reached. Please read Tkinter understanding mainloop regarding this issue.

A possible solution based on the above:

while True:
tk.update_idletasks()
tk.update()
if login_successful: # or whatever your login check looks like
root.destroy()

You replace the mainloop with your custom loop, which includes a check for a successful login.

Close button tkinter after pressing button?

Just use the master.quit() method!
Example Code:

from tkinter import *

class Test:

def __init__(self):
self.master = Tk()
self.button = Button(self.master, text="Push me!", command=self.closeScreen)
self.button.pack()

def closeScreen(self):
# In your case, you need "root2.quit"
self.master.quit()

test = Test()
mainloop()

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

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()

Can't properly close a GUI window in tkinter

Let's summarize the two immediate mistakes you made. You had your button handlers call close_window, which called window.quit(). window here is a global that refers to your main window, so closing that window kills the app. You need to close the calling dialog window. Second, quit on the main window quits the app. You need destroy to simply close the window.

But there are bigger issues we cannot solve. Your dialog functions do nothing. Both buttons simply close the dialog window, without saving the selection that the user made, and without returning any result. You still have a lot of code to write, and we haven't written it here.

def close_window(dlg):
dlg.destroy()

def open_win_delete():
new= Tk()
new.geometry("750x250")
new.title("New Window")
#Create a Label in New window
Label(new, text="Are you sure you want to delete this friend?", font=('Helvetica 17 bold')).grid(row=0,column=2,sticky=NE)
Button(new, text="Yes",width=6, font="none 12 bold", command=lambda: close_window(new)) .grid(row=1,column=2,sticky=NE)
Button(new, text="No",width=6, font="none 12 bold", command=lambda: close_window(new)) .grid(row=1,column=3,sticky=NE)


def open_win_block():
new= Tk()
new.geometry("750x250")
new.title("New Window")
#Create a Label in New window
Label(new, text="Are you sure you want to block this friend?", font=('Helvetica 17 bold')).grid(row=0,column=2,sticky=NE)
Button(new, text="Yes",width=6, font="none 12 bold", command=lambda: close_window(new)) .grid(row=1,column=2,sticky=NE)
Button(new, text="No",width=6, font="none 12 bold", command=lambda: close_window(new)) .grid(row=1,column=3,sticky=NE)

How do I close a tkinter window automatically, after using a button to export a file

Change the exportCSV() to:

def exportCSV ():
global df

export_file_path = filedialog.asksaveasfilename(defaultextension='.csv')
Raw_dataframe.to_csv (export_file_path, index = None, header=True)

root.destroy() #!make sure it is called INSIDE the function


Related Topics



Leave a reply



Submit