Reputation: 87
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()
Upvotes: 2
Views: 554
Reputation: 78
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()
Upvotes: 2