Im trying to close my login wondow and open my register window once I click the sign up button but it doesn't destroy the login window
Here is my login code
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import PIL
from PIL import ImageTk
from PIL import Image
import register
import pymysql
class Login:
def __init__(self,root):
self.root = root
self.root.title("Scheduling Management System")
self.root.geometry("1350x768+0+0")
self.root.resizable(False, False)
self.txt_user = StringVar()
self.txt_pass = StringVar()
self.bg = ImageTk.PhotoImage(file="Images/bgimage.jpg")
bg = Label(self.root, image=self.bg).place(x=0, y=0, relwidth=1, relheight=1)
framelogin = Frame(self.root, bg="white")
framelogin.place(x=450, y=100, height=500, width=700)
title = Label(framelogin, text="Login Here", font=("Arial", 30, "bold"), fg="orange", bg="white").place(x=90,
y=30)
nexttitle = Label(framelogin, text="Scheduling Staff System", font=("Times New Roman", 18, "bold"), fg="orange",
bg="white").place(x=90, y=100)
userlabel = Label(framelogin, text="Username", font=("Arial", 15, "bold"), fg="gray", bg="white").place(x=90,
y=140)
self.txt_user = Entry(framelogin, textvariable=self.txt_user, font=("times new roman", 15), bg="lightgray")
self.txt_user.place(x=90, y=170, width=350, height=35)
passlabel = Label(framelogin, text="Password", font=("Arial", 15, "bold"), fg="gray", bg="white").place(x=90,
y=210)
self.txt_pass = Entry(framelogin, textvariable=self.txt_pass, font=("times new roman", 15), show="*",
bg="lightgray")
self.txt_pass.place(x=90, y=240, width=350, height=35)
forget = Button(framelogin, text="Forgot Password", bg="white", fg="orange", font=("trebuchet ms", 12)).place(
x=90, y=305)
reglabel = Label(framelogin, text="Don't Have an Account?", font=("trebuchet ms", 12, "bold"), fg="orange",
bg="white").place(x=320, y=310)
registerbutton = Button(framelogin, text="Sign Up", command=self.register, bg="white", fg="orange",
font=("trebuchet ms", 12)).place(x=510, y=305)
loginbutton = Button(framelogin, text="Login", command=self.login, fg="white", bg="orange",
font=("sans serif ms", 20)).place(x=90, y=350, width="100", height="40")
def login(self):
if self.txt_user.get() == "" or self.txt_pass.get() == "":
messagebox.showerror("Error", "Please fill up all fields!")
def register(self):
register.RegisterForm()
if __name__ == "__main__":
root = Tk()
obj = Login(root)
root.mainloop()
Here is my register code
from tkinter import *
from tkinter import ttk, messagebox
import PIL
import pymysql
from PIL import ImageTk
from PIL import Image
import login
class Register:
def __init__(self, root):
self.root = root
...
btn = Button(frame1,image=self.btn, bd=0, command = self.registerdata,cursor = "hand2").place(x=50, y = 420)
def registerdata(self):
if self.text_fname.get()=="" or self.text_lname.get()=="" or self.text_contact.get()=="" or self.text_email.get()=="" or self.cmbquestion.get()=="Select" or self.text_pwd.get()=="" or self.text_cfmpwd.get()=="":
messagebox.showerror("Error","All fields are required!",parent=self.root)
elif self.text_pwd.get()!=self.text_cfmpwd.get():
messagebox.showerror("Error","Passwords must be the same!",parent=self.root)
else:
try:
con=pymysql.connect(host="localhost",user="root",password="",database="employee")
cur=con.cursor()
cur.execute("select * from employeelist where email=%s", self.text_email.get())
row=cur.fetchone()
print(row)
if row!=None:
messagebox.showerror("Error","User Already Exists. Please Register With a New Email",parent=self.root)
else:
cur.execute("insert into employeelist (fname,lname,contact,email,question,answer,password) values(%s,%s,%s,%s,%s,%s,%s)",
(self.text_fname.get(),self.text_lname.get(),self.text_contact.get(),self.text_email.get(),self.cmbquestion.get(),self.text_answer.get(),self.text_pwd.get()))
con.commit() #do changes to database
con.close()
messagebox.showinfo("Success","Registration Successful",parent=self.root)
except Exception as ex:
messagebox.showerror("Error",f"Error due to: {str(ex)}",parent=self.root)
l = login
l.Login(root)
def RegisterForm():
win = Toplevel()
obj = Register(win)
if __name__ == "__main__":
root = Tk()
obj = Register(root)
root.mainloop()
Any ideas on how to do so as currently I'm only able to see both windows instead of destroying login window and opening register window?
Firstly add self.root.destroy() to the register method in the login file.
This will destroy the login Tk instance.
To avoid the extra window when the register window opens, change win = Toplevel() in RegisterForm to win = Tk(). Toplevel needs a Tk window so it made an extra window, so we need to create a Tk instance instead.
Related
I'm new to python and decided to fiddle about with a bit of GIU and was wondering how can I switch between frames in a different file dynamically? I've tried adding command=Navigator.change_to_page(self, createMenuFrame) to a button but for some reason, it just combines the frames into one. Is the way I'm trying to do this doable or better to stick with a single main.py file?
I've structured my project in the following way:
main.py:
from tkinter import *
import views.viewMaker as viewMaker
root = Tk()
root.geometry("1200x700")
root.resizable(0, 0)
# Main Frame
mainFrame = Frame(root, bg="gray", width=1200, height=700)
mainFrame.pack()
mainFrame.pack_propagate(0)
viewMaker.ViewMaker.define_views(mainFrame)
root.mainloop()
views/viewMaker.py:
from tkinter import *
import commands.navigator as Navigator
class ViewMaker:
def define_views(self):
mainMenuFrame = Frame(self, bg="white", width=300, height=700) #Define Main Menu
createMenuFrame = Frame(self, bg="white", width=300, height=700) #Define Creator Menu
ViewMaker.populate_main_menu(mainMenuFrame, createMenuFrame) #Populate Main Menu
ViewMaker.populate_create_menu(createMenuFrame) #Populate Create Menu
mainMenuFrame.pack()
mainMenuFrame.pack_propagate(0)
def populate_main_menu(self, createMenuFrame): #Define Main Menu Design
mainMenuTitle = Label(self, text="Title", bg="white", font=("Georgia", 16, "bold"))
mainMenuTitle.pack(pady=25)
generateButton = Button(self, text="Generate New", width=300, font=("Georgia", 12, "bold"))
generateButton.pack(pady=5, side=TOP)
createButton = Button(self, text="Create New", width=300, font=("Georgia", 12, "bold"), command=Navigator.change_to_page(self, createMenuFrame))
createButton.pack(pady=5, side=TOP)
quitButton = Button(self, text="Quit", width=300, font=("Georgia", 12, "bold"), command=self.master.master.destroy)
quitButton.pack(pady=25, side=BOTTOM)
def populate_create_menu(self): #Define Create Menu Design
createMenuTitle = Label(self, text="Create New", bg="white", font=("Georgia", 16, "bold"))
createMenuTitle.pack(pady=25)
commands/navigator.py:
from tkinter import *
def change_to_page(self, newPage):
newPage.pack()
newPage.pack_propagate()
self.pack_forget()
Note that command=Navigator.change_to_page(self, createMenuFrame) will execute Navigattor.change_to_page() immediately which shows the createMenuFrame.
Change it to command=lambda: Navigator.change_to_page(self, createMenuFrame) instead.
I'm relatively new to Tkinter and I need help.
I have created a Connect database window when a button(login) is clicked from the parent window. The new window is the login.py(file). But it's not opening
connect database.py below;
from tkinter import *
from tkinter import ttk
from PIL import Image,ImageTk
import os
import pickle
import mysql.connector as sql
from tkinter import messagebox
import login
def login1():
host = host_entry.get()
port = port_entry.get()
username = username_entry.get()
password = password_entry.get()
database="cars"
spec=sql.connect(host=host,user=username,password=password,port=port)
if spec.is_connected():
messagebox.showinfo("Connected","Database connected Sucessfully")
else:
messagebox.showerror("Exists", "Database is already connected")
spec.close()
root = Tk()
root.geometry("1067x600")
root.configure(background="black")
root.resizable(False, False)
root.title("School Diaries")
#background image
bg = ImageTk.PhotoImage(file="files\Sublime Light1.jpg")
lbl_bg = Label(root,image=bg)
lbl_bg.place(x=0,y=0,relwidth=1,relheight=1)
#Labels
host_label = Label(root, text="Host Name ", bg="white", fg="#4f4e4d",font=("yu gothic ui", 12, "bold"))
host_label.place(x=675, y=115)
host_entry = Entry(root, highlightthickness=0, relief=FLAT, bg="white", fg="#6b6a69",font=("yu gothic ui semibold", 12))
#host_entry.insert(0, "localhost")
host_entry.place(x=687, y=139, width=145)
port_label = Label(root, text="Port ", bg="white", fg="#4f4e4d",font=("yu gothic ui", 13, "bold"))
port_label.place(x=675, y=190)
port_entry = Entry(root, highlightthickness=0, relief=FLAT, bg="white", fg="#6b6a69",font=("yu gothic ui semibold", 12))
#port_entry.insert(0, "3307")
port_entry.place(x=690, y=213, width=145)
username_label = Label(root, text="Username ", bg="white", fg="#4f4e4d",font=("yu gothic ui", 13, "bold"))
username_label.place(x=675, y=265)
username_entry = Entry(root, highlightthickness=0, relief=FLAT, bg="white", fg="#6b6a69",font=("yu gothic ui semibold", 12))
#username_entry.insert(0, "root")
username_entry.place(x=687, y=287, width=145)
password_label = Label(root, text="Password ", bg="white", fg="#4f4e4d",font=("yu gothic ui", 13, "bold"))
password_label.place(x=675, y=338)
password_entry = Entry(root, highlightthickness=0, relief=FLAT, bg="white", fg="#6b6a69",font=("yu gothic ui semibold", 12))
#password_entry.insert(0, "root")
password_entry.place(x=687, y=361, width=145)
#buttons
submit = ImageTk.PhotoImage(file='Pics\submit.png')
submit_button = Button(root, image=submit,font=("yu gothic ui", 13, "bold"), relief=FLAT, activebackground="white",borderwidth=0, background="white", cursor="hand2",command=login1)
submit_button.place(x=655, y=440)
login = ImageTk.PhotoImage(file='Pics\login.png')
login_button = Button(root, image=login,font=("yu gothic ui", 13, "bold"), relief=FLAT, activebackground="white",borderwidth=0, background="white", cursor="hand2",commmand=login)
login_button.place(x=785, y=442)
root.mainloop()
image of connect database
login.py file below ;
from tkinter import *
from tkinter import ttk
from PIL import Image,ImageTk
import os
import pickle
import mysql.connector as sql
from tkinter import messagebox
import user_inter
def login():
host = user_inter.host_entry.get()
port = user_inter.port_entry.get()
username = username_entry.get()
password = password_entry.get()
spec=sql.connect(host=host,user=username,password=password,port=port)
if spec.is_connected():
messagebox.showinfo("Connected","Database connected Sucessfully")
else:
messagebox.showerror("Exists", "Failed")
mycur=spec.cursor()
mycur.execute()
root = Tk()
root.geometry("1067x600")
root.configure(background="black")
root.resizable(False, False)
root.title("School Diaries")
#background
bg = ImageTk.PhotoImage(file="files\login.jpg")
lbl_bg = Label(root,image=bg)
lbl_bg.place(x=0,y=0,relwidth=1,relheight=1)
#Labels
login_lbl = Label(root, text="Login", bg="white", fg="#4f4e4d",font=("San Francisco", 45))
login_lbl.place(x=757,y=120)
username_label = Label(root, text="Username ", bg="white", fg="#4f4e4d",font=("yu gothic ui", 13, "bold"))
username_label.place(x=675, y=190)
username_entry = Entry(root, highlightthickness=0, relief=FLAT, bg="white", fg="#6b6a69",font=("yu gothic ui semibold", 12))
#username_entry.insert(0, "root")
username_entry.place(x=695, y=215, width=190)
password_label = Label(root, text="Password ", bg="white", fg="#4f4e4d",font=("yu gothic ui", 13, "bold"))
password_label.place(x=675, y=280)
password_entry = Entry(root, highlightthickness=0, relief=FLAT, bg="white", fg="#6b6a69",font=("yu gothic ui semibold", 12))
#password_entry.insert(0, "root")
password_entry.place(x=692, y=305, width=190)
login = ImageTk.PhotoImage(file='Pics\login.png')
login_button = Button(root, image=login,font=("yu gothic ui", 13, "bold"), relief=FLAT, activebackground="white",borderwidth=0, background="white", cursor="hand2",command=login)
login_button.place(x=770, y=390)
root.mainloop()
image of login page
PS ; connect database.py is mentioned in the code as user_intern.py
0
now my doubt is ;
I have created a login.py page using tkinter and I have created a connect database.py page also, so my doubt is I have a button called login in connect database window, now the how to give argument such as if I click the login button the screen shd change to my login.py screen .....hope u understand my doubt
when I click login the login.py shd execute in the parent window itself
Thanks,
any edits in code to get my output is welcomed
when i click login in connect database the login windows shd open in parent window itself
as mentioned by #ablmmcu in comment, tkinter only has 1 root, and it should be in main program
the other point is, i suggest using tkinter.TopLevel() and use it as a window to your database when you press login button and it succeed at logging in.
more info about TopLevel:
Toplevel widgets work as windows that are directly managed by the window manager. They do not necessarily have a parent widget on top of them.
Your application can use any number of top-level windows.
source: https://www.tutorialspoint.com/python/tk_toplevel.htm
on a side note : you place TopLevel windows inside the root.
Im trying to enter to the menu window but whenever I do so I get the cant invoke frame command. I am not sure if there is an error regarding with my .mainloop() function
Here is my login code
class Login:
global user
global pwd
def __init__(self,root):
self.root = root
self.root.title("Scheduling Management System")
self.root.geometry("1350x768+0+0")
self.root.resizable(False, False)
self.txt_user = StringVar()
self.txt_pass = StringVar()
self.bg = ImageTk.PhotoImage(file="Images/bgimage.jpg")
bg = Label(self.root, image=self.bg).place(x=0, y=0, relwidth=1, relheight=1)
framelogin = Frame(self.root, bg="white")
framelogin.place(x=450, y=100, height=500, width=700)
registerbutton = Button(framelogin, text="Sign Up", command=self.register, bg="white", fg="orange",
font=("trebuchet ms", 12)).place(x=510, y=305)
loginbutton = Button(framelogin, text="Login", command=self.login, fg="white", bg="orange",
font=("sans serif ms", 20)).place(x=90, y=350, width="100", height="40")
def login(self):
global con
user = self.txt_user.get().strip()
pwd = self.txt_pass.get().strip()
if user == "" or pwd == "":
messagebox.showerror("Error", "Please fill up all fields!")
else:
try :
con=pymysql.connect(host="localhost",user="root",password="",database="employee")
cur=con.cursor()
cur.execute("select 1 from employeelist where username=%s and password=%s", (user,pwd))
if cur.rowcount == 1:
messagebox.showinfo("Success", "Login Successful", parent=self.root)
self.menu()
else:
messagebox.showerror("Error", "Wrong Username or Password. Please try again!")
except Exception as ex:
messagebox.showerror("Error",f"Error due to: {str(ex)}",parent=self.root)
finally:
con.close()
def register(self):
self.root.destroy()
register.RegisterForm()
def menu(self):
self.root.destroy()
menu.MenuForm()
def LoginForm():
win = Tk()
obj = Login(win)
if __name__ == "__main__":
root = Tk()
obj = Login(root)
root.mainloop()
Here is my menu code
from tkinter import *
from tkinter import ttk, messagebox
import PIL
from PIL import ImageTk
from PIL import Image
import login
class Menu:
def __init__(self,root):
self.root = root
self.root.title("Main Menu")
self.root.geometry("1350x768+0+0")
self.bg = ImageTk.PhotoImage(file="Images/bgimage.jpg")
bg = Label(self.root, image=self.bg).place(x=0, y=0, relwidth=1, relheight=1)
framemenu = Frame(self.root, bg="white")
framemenu.place(x=450, y=100, height=500, width=700)
welcometitle = Label(framemenu, text="Welcome " + login.Login.user, font=("Arial", 30, "bold"), fg="orange", bg="white").place(x=470,
y=120)
def MenuForm():
win = Tk()
obj = Menu(win)
if __name__ == "__main__":
root = Tk()
obj = Menu(root)
root.mainloop()
I cant seem to identify the issue as Im trying to redirect the users once it has login to the menu page
I have been on this for some time now, have tried so many methods I could find online but non seems to solve my problem. My Toplevel() window displays nothing. This is supposed to be part of my program at a certain point. Had to copy the code out and summarize it this way yet it doesn't work. I think i am missing something
from tkinter import *
# from tkinter import ttk
# import sqlite3
# conn = sqlite3.connect('shengen.db')
# c = conn.cursor()
# q = c.execute(
# "SELECT email FROM users WHERE email=('ichibuokem#gmail.com');")
# conn.commit()
# for i in q:
# print(list(i))
def portal_start():
portal = Toplevel(root)
portal.title("Visa Application Form")
portal.geometry("600x600")
portal.iconbitmap("...\Visa-Application-Management-System\icon.ico")
Label(portal, text="", bg="grey", height="2",
width="900", font=("Calibri", 14)).pack(pady=10)
spc = Label(portal, text="")
spc.pack()
portal_notebook = ttk.Notebook(portal)
portal_notebook.pack()
page1 = Frame(portal_notebook, width=600, height=600)
page2 = Frame(portal_notebook, width=600, height=600)
page3 = Frame(portal_notebook, width=600, height=600)
page4 = Frame(portal_notebook, width=600, height=600)
summary = Frame(portal_notebook, width=600, height=600)
page1.pack(fill="both", expand=1)
page2.pack(fill="both", expand=1)
page3.pack(fill="both", expand=1)
page4.pack(fill="both", expand=1)
summary.pack(fill="both", expand=1)
portal_notebook.add(page1, text="Basic Details")
portal_notebook.add(page2, text="Sponsorship")
portal_notebook.add(page3, text="Medicals")
portal_notebook.add(page4, text="References")
portal_notebook.add(summary, text="Summary")
# ============================================Portal End===================================================
# =============================================Instantiation window=======================================
def window():
global root
root = Tk()
root.geometry("900x700")
root.title("Welcome Page")
root.iconbitmap("..\Visa-Application-Management-System\icon.ico")
Label(root, text="Welcome To Python Visa Application Portal! \n\nTo check your visa application status, file a new application or update your application, \nLogin or Create an account.",
fg="white", bg="grey", height="6", width="900", font=("Calibri", 14)).pack()
Label(root, text="").pack()
Label(root, text="").pack()
Label(root, text="").pack()
Label(root, text="").pack()
Label(root, text="").pack()
Button(root, text="Login", width=20, font=(
"bold", 14)).pack()
Label(root, text="").pack()
Button(root, text="Create Account", width=20,
font=("bold", 14)).pack()
Label(root, text="").pack()
Label(root, text="").pack()
Label(root, text="Copyright 2020. All Rights Reserved \nWith Luv From Group 3",
font=("Calibri", 8)).pack()
Button(root, text="Test Window", width=20,
font=("bold", 14), command=portal_start).pack()
Label(root, text="").pack()
root.mainloop()
window()
add this to the top your your code
from tkinter import ttk
It should work perfectly then
I was wondering if someone could help me as I am fairly new to Tkinter and got some good help on here before.
My query is that I am trying to make a budget calculator sort of program and am using Tkinter. I am wondering how do you get user inputs where the user can click on a button called "Incomes" or "Expenses" and then they can input all their numbers and it will be printed below in the form of a table.
My code is below any information will really help me and also any other points you can point out about my code so far will be greatly appreciated!
from time import sleep
from tkinter import *
from tkinter import messagebox, ttk, Tk
root = Tk()
class GUI():
def taskbar(self):
menu = Menu(root)
file = Menu(menu)
root.config(menu=file)
file.add_command(label="Exit", command=self.exit_GUI)
file.add_command(label="Information", command=self.info_popup)
menu.add_cascade(label="File", menu=file)
def Main_Menu(self):
topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
Income_button = Button(topFrame, text="Enter your incomes", command=self.Income)
Expense_button = Button(topFrame, text="Enter your expenses", command=self.Expense)
Total_button = Button(bottomFrame, text="View Results", command=self.Total)
Income_button.pack()
Expense_button.pack()
Total_button.pack()
def Income(self):
Income_heading = Label(Toplevel(root), text="Please enter the incomes below!", font=("arial", 50, "bold"), fg="blue").pack()
def Expense(self):
Expense_heading = Label(Toplevel(root), text="Please enter the expenses below!", font=("arial", 50, "bold"), fg="blue").pack()
def Total(self):
pass
def exit_GUI(self):
exit()
def info_popup(self):
pass
g = GUI()
g.taskbar()
g.Main_Menu()
#g.Income()
#g.Expense()
g.Total()
g.info_popup()
root.mainloop()
You should use class attributes to hold the values. Then we can use a combination of lambda, entry, and a function to set those values.
This below example will show you how one can set values from a top level window inside the class.
import tkinter as tk
class GUI():
def __init__(self):
menu = tk.Menu(root)
file = tk.Menu(menu)
root.config(menu=file)
file.add_command(label="Exit", command=self.exit_GUI)
file.add_command(label="Information", command=self.info_popup)
menu.add_cascade(label="File", menu=file)
self.income_var = 0
self.expense_var = 0
self.total_var = 0
top_frame = tk.Frame(root)
top_frame.pack()
bottom_frame = tk.Frame(root)
bottom_frame.pack(side="bottom")
tk.Button(top_frame, text="Enter your incomes", command=self.income).pack()
tk.Button(top_frame, text="Enter your expenses", command=self.expense).pack()
tk.Button(bottom_frame, text="View Results", command=self.total).pack()
def set_vars(self, entry, var):
if var == "income":
self.income_var = entry.get()
print(self.income_var)
if var == "expense":
self.expense_var = entry.get()
print(self.expense_var)
if var == "total":
self.total_var = entry.get()
print(self.total_var)
def income(self):
top = tk.Toplevel(root)
tk.Label(top, text="Please enter the incomes below!", font=("arial", 12, "bold"), fg="blue").pack()
entry = tk.Entry(top)
entry.pack()
tk.Button(top, text="Submit", command=lambda: (self.set_vars(entry, "income"), top.destroy())).pack()
def expense(self):
top = tk.Toplevel(root)
tk.Label(top, text="Please enter the expenses below!", font=("arial", 12, "bold"), fg="blue").pack()
entry = tk.Entry(top)
entry.pack()
tk.Button(top, text="Submit", command=lambda: (self.set_vars(entry, "expense"), top.destroy())).pack()
def total(self):
pass
def exit_GUI(self):
self.destroy()
def info_popup(self):
pass
root = tk.Tk()
g = GUI()
root.mainloop()
The widget to enter information in Tkinter is the widget Entry. For get the text you could use get(). Example:
def income_func(self, event):
text = Income_entry.get() #For get the text into the entry
def Income(self):
top_lvl = Toplevel(root)
Income_heading = Label(top_lvl , text="Please enter the incomes below!", font=("arial", 50, "bold"), fg="blue").pack()
Income_entry = Entry(top_lvl)
Income_entry.pack()
Income_entry.bind("<Key-Return>", income_func) #When user press `enter` this call to income_func with argument `event`