Python - Tkinter how to close window after button is pressed?How do I copy a file in Python?How can I safely create a nested directory?How do I parse a string to a float or int in Python?How to get the current time in PythonHow can I make a time delay in Python?How do I get the number of elements in a list in Python?How do I concatenate two lists in Python?How do I install pip on Windows?ttk tkinter multiple frames/windowsHow do I lowercase a string in Python?

How could Dwarves prevent sand from filling up their settlements

Why does snapping your fingers activate the Infinity Gauntlet?

Is it a good idea to teach algorithm courses using pseudocode instead of a real programming language?

Can the word crowd refer to just 10 people?

What does this 'x' mean on the stem of the voice's note, above the notehead?

On a piano, are the effects of holding notes and the sustain pedal the same for a single chord?

Parse a C++14 integer literal

How could the B-29 bomber back up under its own power?

What were the "pills" that were added to solid waste in Apollo 7?

Very serious stuff - Salesforce bug enabled "Modify All"

Greek theta instead of lower case þ (Icelandic) in TexStudio

Failing students when it might cause them economic ruin

Does the Aboleth have expertise in history and perception?

If you attack a Tarrasque while swallowed, what AC do you need to beat to hit it?

Why does the U.S military use mercenaries?

Vehemently against code formatting

Is there any official Lore on Keraptis the Wizard, apart from what is in White Plume Mountain?

Can 2 light bulbs of 120V in series be used on 230V AC?

Warped chessboard

Good examples of "two is easy, three is hard" in computational sciences

Bash - Execute two commands and get exit status 1 if first fails

How to make labels automatically scale in size to fit between 2 coordinates in tikz?

Richard's Favourite TV Programme

Better than Rembrandt



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


How do I copy a file in Python?How can I safely create a nested directory?How do I parse a string to a float or int in Python?How to get the current time in PythonHow can I make a time delay in Python?How do I get the number of elements in a list in Python?How do I concatenate two lists in Python?How do I install pip on Windows?ttk tkinter multiple frames/windowsHow do I lowercase a string in Python?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








2















So there is a first window for the user to log into. Once the user has logged in they can start the game by clicking the "continue" button. The command of this button is set to the function con which should close the window using the window.destroy() function however whenever I try to click it I always receive an error stating "window is not defined"



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):
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]+"!")
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))
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()









share|improve this question






















  • That is simply because your window is a local variable. You will have to declare global when you create your window.

    – Henry Yik
    Mar 23 at 18:49











  • The problem is I have multiple windows

    – J.Peggy
    Mar 23 at 18:54











  • Normally you shouldn't be creating more than one instance of Tk. Just use Toplevel for additional windows.

    – Henry Yik
    Mar 23 at 19:01

















2















So there is a first window for the user to log into. Once the user has logged in they can start the game by clicking the "continue" button. The command of this button is set to the function con which should close the window using the window.destroy() function however whenever I try to click it I always receive an error stating "window is not defined"



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):
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]+"!")
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))
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()









share|improve this question






















  • That is simply because your window is a local variable. You will have to declare global when you create your window.

    – Henry Yik
    Mar 23 at 18:49











  • The problem is I have multiple windows

    – J.Peggy
    Mar 23 at 18:54











  • Normally you shouldn't be creating more than one instance of Tk. Just use Toplevel for additional windows.

    – Henry Yik
    Mar 23 at 19:01













2












2








2








So there is a first window for the user to log into. Once the user has logged in they can start the game by clicking the "continue" button. The command of this button is set to the function con which should close the window using the window.destroy() function however whenever I try to click it I always receive an error stating "window is not defined"



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):
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]+"!")
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))
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()









share|improve this question














So there is a first window for the user to log into. Once the user has logged in they can start the game by clicking the "continue" button. The command of this button is set to the function con which should close the window using the window.destroy() function however whenever I try to click it I always receive an error stating "window is not defined"



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):
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]+"!")
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))
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()






python tkinter






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 23 at 18:43









J.PeggyJ.Peggy

426




426












  • That is simply because your window is a local variable. You will have to declare global when you create your window.

    – Henry Yik
    Mar 23 at 18:49











  • The problem is I have multiple windows

    – J.Peggy
    Mar 23 at 18:54











  • Normally you shouldn't be creating more than one instance of Tk. Just use Toplevel for additional windows.

    – Henry Yik
    Mar 23 at 19:01

















  • That is simply because your window is a local variable. You will have to declare global when you create your window.

    – Henry Yik
    Mar 23 at 18:49











  • The problem is I have multiple windows

    – J.Peggy
    Mar 23 at 18:54











  • Normally you shouldn't be creating more than one instance of Tk. Just use Toplevel for additional windows.

    – Henry Yik
    Mar 23 at 19:01
















That is simply because your window is a local variable. You will have to declare global when you create your window.

– Henry Yik
Mar 23 at 18:49





That is simply because your window is a local variable. You will have to declare global when you create your window.

– Henry Yik
Mar 23 at 18:49













The problem is I have multiple windows

– J.Peggy
Mar 23 at 18:54





The problem is I have multiple windows

– J.Peggy
Mar 23 at 18:54













Normally you shouldn't be creating more than one instance of Tk. Just use Toplevel for additional windows.

– Henry Yik
Mar 23 at 19:01





Normally you shouldn't be creating more than one instance of Tk. Just use Toplevel for additional windows.

– Henry Yik
Mar 23 at 19:01












1 Answer
1






active

oldest

votes


















2














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





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55317187%2fpython-tkinter-how-to-close-window-after-button-is-pressed%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














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





    share|improve this answer





























      2














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





      share|improve this answer



























        2












        2








        2







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





        share|improve this answer















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






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 23 at 19:06

























        answered Mar 23 at 19:01









        wafiwafi

        618




        618





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55317187%2fpython-tkinter-how-to-close-window-after-button-is-pressed%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript