Tkinter and SQlite project - python

from tkinter import *
from database import *
def Control_():
var1 = NameE.get()
var2 = LastnameE.get()
var3 = UsernameE.get()
var4 = PasswordE.get()
search = KullaniciAra(var3)
if search == None:
kullanici_ekle(var1,var2,var3,var4)
Login_Page()
else:
ErrorLabel = Label(win,text="This username is taken.")
ErrorLabel.grid(row=8,column=1)
def Login_Page():
def on_login():
var3 = UsernameE2.get()
var4 = PasswordE2.get()
search2 = KullaniciAra(var3)
if search2 == var4:
print("Done!")
win.destroy()
new_win = Tk()
new_win.title("T Messenger L")
new_win.geometry("200x200")
UsernameL2 = Label(new_win,text="Username",fg="black",bg="lightgray")
UsernameL2.grid(row=0,column=0)
UsernameE2 = Entry()
UsernameE2.grid(row=0,column=1)
PasswordL2 = Label(new_win,text="Password",fg="black",bg="lightgray")
PasswordL2.grid(row=1,column=0)
PasswordE2 = Entry()
PasswordE2.grid(row=1,column=1)
Button2 = Button(new_win,text="Login",command=on_login)
Button2.grid(row=2,column=1)
new_win.mainloop()
Tablo_olustur()
win = Tk()
win.title("T Messenger R")
win.geometry("200x200")
NameL = Label(win,text="Name",fg="black",bg="lightgray")
NameL.grid(row=1,column=0)
NameE = Entry()
NameE.grid(row=1,column=1)
LastnameL = Label(win,text="Lastname",fg="black",bg="lightgray")
LastnameL.grid(row=2,column=0)
LastnameE = Entry()
LastnameE.grid(row=2,column=1)
UsernameL = Label(win,text="Username",fg="black",bg="lightgray")
UsernameL.grid(row=3,column=0)
UsernameE = Entry()
UsernameE.grid(row=3,column=1)
PasswordL = Label(win,text="Password",fg="black",bg="lightgray")
PasswordL.grid(row=4,column=0)
PasswordE = Entry()
PasswordE.grid(row=4,column=1)
theLabel = Label(win,text="Login here",fg="blue",cursor="hand2",font=("TkDefaultFont",12,"underline"))
theLabel.grid(row=5,column=1)
theLabel.bind("<Button-1>", lambda event: Login_Page())
Button1 = Button(win,text="Register",command=Control_)
Button1.grid(row=6,column=1)
win.mainloop()
I wanted to make "login here" text with .bind() it worked as I want, it opened Login_Page() then even If I enter correct username and password when I click "Login" button nothing happens. What I want is "When 'login' button clicked and if username and password on my database and true open new page" and the new page name will be Vote_Page() cause user will choose like Find user, Update password, Delete acc etc

When writing a dialog box, you should use a Toplevel window as its base, not Tk. There should onle be one Tk instance in your program.
The implementation of FileDialog in cpython/filedialog.py is a nice example of how to implement a dialog in a class.

Related

How do i move to another section of my program?

I have built a login system using Tkinter and Sqlite3 for Python and I need to move on to another section of code once the login flow is complete. At the point in the 'test' function where I've added a comment, I need a separate python file (eg somefile.py) to run its code. How is best to do this? Your help is appreciated! Code below:
from tkinter import *
import Check_credentials as check
import New_user_screen as create
def test():
username = user.get()
password = pword.get()
global valid
valid = False
valid=check.check_user(username,password)
print(valid)
if valid == True:
login.destroy()
'launch main program' #Here is where i need the next section of the program to be run but ideally not as another function in this proram
print('Incorrect login getails\nPlease try again!')
def screen():
global login
login = Tk()
login.title('User Login')
login.geometry('300x180')
login.configure(background = 'white')
global user
global pword
message = Label(login,
text = 'Please enter username and password below',
bg='white')
message.pack()
label1 = Label(login,
text = 'Username',
bg='white')
label1.place(x=0,y=50)
user = Entry(login)
user.place(x=100,y=50)
label2 = Label(login,
text = 'Password',
bg='white')
label2.place(x=0,y=90)
pword = Entry(login)
pword.place(x=100,y=90)
confirm = Button(login,
text='Sign In',
fg='white',
bg='blue',
command = test)
confirm.place(x=50,y=130)
new = Button(login,
text='New User',
fg='white',
bg='blue',
command = create.screen)
new.place(x=120,y=130)
When the login is valid, it will go to the the function greeting in the class Main
from tkinter import *
import Check_credentials as check
import New_user_screen as create
class Login:
def test():
username = user.get()
password = pword.get()
global valid
valid = False
valid=check.check_user(username,password)
print(valid)
if valid == True:
login.destroy()
Main.greeting() #Here is where i need the next section of the program to be run but ideally not as another function in this proram
def screen():
global login
login = Tk()
login.title('User Login')
login.geometry('300x180')
login.configure(background = 'white')
global user
global pword
message = Label(login,
text = 'Please enter username and password below',
bg='white')
message.pack()
label1 = Label(login,
text = 'Username',
bg='white')
label1.place(x=0,y=50)
user = Entry(login)
user.place(x=100,y=50)
label2 = Label(login,
text = 'Password',
bg='white')
label2.place(x=0,y=90)
pword = Entry(login)
pword.place(x=100,y=90)
confirm = Button(login,
text='Sign In',
fg='white',
bg='blue',
command = test)
confirm.place(x=50,y=130)
new = Button(login,
text='New User',
fg='white',
bg='blue',
command = create.screen)
new.place(x=120,y=130)
class Main:
def greeting():
print("You Have Logged In Successfully")

Why does python show "TclError : can't invoke "place" command: application has been destroyed" in the following code

import tkinter as tk
def close_window():
print ("")
window.destroy()
window = tk.Tk()
window.geometry("750x350")
username = tk.Label(window, text = "Enter Username")
password = tk.Label(window, text = "Enter Password")
input1 = tk.Entry(window)
input2 = tk.Entry(window, show = "*")
confirm = tk.Button(text="Confirm", command = close_window())
input1.place(x=400, y=35)
input2.place(x=400, y=65)
username.place(x=150, y=35)
password.place(x=150, y=65)
confirm.place(x=400, y=100)
confirm.pack()
window.mainloop()
I am trying to make a forum which closes itself once you click confirm. Also, i use spyder (just in case) and i have just started the concept of tkinter. I tried to find the answer on google but it was not so successful.
you're calling "close_window()" in this line: "confirm = tk.Button(text="Confirm", command = close_window()) "

defined code executes before called upon using tkinter button [duplicate]

This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 2 years ago.
I am working on a program that lets users store their usernames and passwords, and hashes the plaintext where they are stored (hence the commented out hashing code). However, I am using tkinter for the GUI, and one of my buttons runs a defined function before it's called. (ignore all seemingly random comments please)
import basehash
import tkinter
import tkinter as tk
import os
from tkinter import*
from tkinter import messagebox
from string import ascii_lowercase
userPaths = ['./usernames2.txt', './username.txt', './usernames3.txt']
passPaths = ['./Passwords2.txt', './Passwords.txt', './Passwords3.txt']
#create new doc and assign doc array
# use an array for password of paths where the password is stored on a plaintext file
password = ("test")
usernameguess1 = ("")
passwordguess1 = ("")
loggedin = 0
activeUser = ""
activeUserNum = 0
hashbase = basehash.base52()
LETTERS = {letter: str(index) for index, letter in enumerate(ascii_lowercase, start=1)}
def alphabet_position(text):
text = text.lower()
numbers = [LETTERS[character] for character in text if character in LETTERS]
return ''.join(numbers)
def loginpage():
#Gui Formatting
root = tkinter.Toplevel()
root.resizable(width=FALSE, height=FALSE)
root.title("HasherTest_V0.1 Login")
root.geometry("300x150")
#Username and password boxes
usernametext = tkinter.Label(root, text="Username:")
usernameguess = tkinter.Entry(root)
passwordtext = tkinter.Label(root, text="Password:")
passwordguess = tkinter.Entry(root, show="*")
usernameguess1 = usernameguess
def trylogin():
print ("Logging In...")
for x in range(0,len(userPaths)):
#get path data here
file1 = open(userPaths[x], "r")
original = file1.read()
file1.close()
if original == usernameguess.get():
userPaths[x] = activeUser
x = activeUserNum
file1 = open(passPaths[activeUserNum], "r")
original = file1.read()
original = hashbase.unhash(original)
file1.close()
if usernameguess.get() == activeUser and alphabet_position(passwordguess.get()) == original:
print ("Success!")
messagebox.showinfo("Success ", "Successfully logged in.")
viewbutton = tkinter.Button(root, text="Veiw Saved Passwords", command=lambda:[root.withdraw()])
viewbutton.pack()
else:
print ("Error: (Incorrect value entered)")
messagebox.showinfo("Error", "Sorry, but your username or password is incorrect. Try again")
#login button
def viewtest():
if loggedin == 1:
messagebox.showinfo("Success ", "Loading Passwords")
else:
messagebox.showinfo("Error", "You need to sign in first!")
#login button
root.deiconify() #shows login window
attemptlogin = tkinter.Button(root, text="Login", command=trylogin)
attemptview = tkinter.Button(root, text="View Stored Passwords", command=viewtest)
usernametext.pack()
usernameguess.pack()
passwordtext.pack()
passwordguess.pack()
attemptlogin.pack()
attemptview.pack()
window.mainloop()
def signuppage():
root2 = tkinter.Toplevel()
root2.resizable(width=FALSE, height=FALSE)
root2.title("HasherTest_V0.1 Login")
root2.geometry("300x150")
#Gui Formatting (again)
root2 = tkinter.Tk()
root2.resizable(width=FALSE, height=FALSE)
root2.title("HasherTest_V0.1")
root2.geometry("300x150")
#Username and password boxes
masterusername = tkinter.Label(root2, text="Enter Master Username:")
masterusernamebox = tkinter.Entry(root2)
masterpassword = tkinter.Label(root2, text="Enter Master Password:")
masterpasswordbox = tkinter.Entry(root2, show="*")
def trysignup():
newuser = str(masterusernamebox.get())
length = len(userPaths)
namepath = './usernames3.txt'
userPaths[length-1] = namepath
newfile = open(namepath, 'w')
newfile.write(newuser)
newfile.close()
password = str(masterpasswordbox.get())
numPass = alphabet_position(password)
print(numPass)
"""hashbase = basehash.base52()
#not taking numPass as an int
#run test 328-i
hashval = hashbase.hash(numPass)
print(hashval)
unhashed = hashbase.unhash(hashval)
print(unhashed)"""
path = './passwords3.txt'
newfile = open(path, 'w')
newfile.write(numPass)
newfile.close()
if newuser == "":
messagebox.showinfo("Error code 0", "No input entered")
else:
return
#login button
mastersignupbutton = tkinter.Button(root2, text="Sign Up 1", command=trysignup())
mastersignupbutton.pack()
masterusername.pack()
masterusernamebox.pack()
masterpassword.pack()
masterpasswordbox.pack()
window.mainloop()
window = tkinter.Tk()
window.resizable(width=FALSE, height=FALSE)
window.title("HasherTest_V0.1")
window.geometry("300x150")
loginbutton = tkinter.Button(window, text="Login", command=lambda:[window.withdraw(), loginpage()])
signupbutton = tkinter.Button(window, text="Sign Up", command=lambda:[window.withdraw(), signuppage()])
loginbutton.pack()
signupbutton.pack()
window.mainloop()
If you run this code, and press the sign up button, then type in a master username and password, it should write them both to a notepad file, and if there is nothing in the box, give an error message. However, neither of these functions are working. When the user presses the first "sign up" button on the main window, it runs the wrong code (somehow) and gives an error code before it should. the error code should show if there is nothing there when "sign up 1" button is pressed on the "enter master username and password" window. I have no clue why the code runs early. Could somebody please reply with the reason why, or even some fixed code? thanks, Tf0R24.
When creating a button, a common error is including the parentheses after the function name. Instead of this:
mastersignupbutton = tkinter.Button(root2, text="Sign Up 1", command=trysignup())
Do this:
mastersignupbutton = tkinter.Button(root2, text="Sign Up 1", command=trysignup)
which is exactly the same but without the parentheses after command=trysingup. If you want to call a function that requires arguments, do this:
tkinter.Button(master, text="text", command=lambda: function_that_requires_arguments(x, y))
change to
mastersignupbutton = tkinter.Button(root2, text="Sign Up 1", command=trysignup)

Change password of login page with tkinter

I'm trying to make a login gui using tkinter, and I want a new window to open when I click on change password.
When the window opens it should prompt the user for a new password, and then change and store the password. Afterwards, it should login again using the changed password.
import tkinter as tk
import tkinter.messagebox as tm
class LoginFrame(tk.Frame):
storedPassword='password'
def __init__(self, master):
super().__init__(master)
#storedPassword='password'
self.label_username = tk.Label(self, text="Username")
self.label_password = tk.Label(self, text="Password")
self.entry_username = tk.Entry(self)
self.entry_password = tk.Entry(self)#, show="*") to help us see new password
self.label_username.grid(row=0)
self.label_password.grid(row=1)
self.entry_username.grid(row=0, column=1)
self.entry_password.grid(row=1, column=1)
self.logbtn = tk.Button(self, text="Login", command=self._login_btn_clicked)
self.logbtn.grid(columnspan=2)
newPassword = self.entry_password.get()
print(newPassword)
self.logbtn = tk.Button(self, text="change_password", command=self.change_password)
self.logbtn.grid(columnspan=2)
def change_password(self,newPassword):
self.new_password = tk.Label(self, text="new password")
self.entry_newpassword = tk.Entry(self)
self.storedPassword=newPassword
print(self.entry_newpassword.get())
def _login_btn_clicked(self):
username = self.entry_username.get()
password = self.entry_password.get()
if username == "admin":
if password == self.storedPassword:
tm.showinfo("Login info", "Welcome admin")
self.storedPassword=self.entry_password.get()
else:
tm.showerror("Login error", "Incorrect password")
else:
tm.showerror("Login error", "Incorrect username")
window= tk.Tk()
lf = LoginFrame(window)
#root = tk.Tk()
#newWindow= LoginFrame(root)
#root.mainloop()
window.mainloop()
Simply destroy the initial window first using window.destroy() and then create a new window in a function when it is called by the button. Continue adding entry widgets and labels as you know and get the new password and run another function to go back to initial page after using root.destroy() to remove change password window.
Here is a simple code showing what I just said:
from tkinter import *
from tkinter import messagebox
storedPassword = 'password'
def loginok(username,password):
global storedPassword
if username == "admin":
if password == storedPassword:
messagebox.showinfo("Login Successful!","Welcome Admin")
else:
messagebox.showerror("Login Failed!","Wrong Password")
else:
messagebox.showerror("Login Failed!","Wrong Username")
def cpass():
global window
window.destroy()
window = Tk()
Label(window,text="Enter new password:").pack()
passn = Entry(window,width=15)
passn.pack()
Button(window,text="OK",command=lambda:chgpass(passn.get())).pack()
window.mainloop()
def chgpass(newpass):
global window
global storedPassword
storedPassword = newpass
window.destroy()
login()
def login():
global window
window = Tk()
Label(window,text="Username:").pack()
usern = Entry(window,width=15)
usern.pack()
Label(window,text="Password:").pack()
passw = Entry(window,width=15,show="*")
passw.pack()
Button(window,text="Login",command=lambda:loginok(usern.get(),passw.get())).pack()
Button(window,text="Forgot",command=cpass).pack()
window.mainloop()
login()

How to create password system in tkinter reading the data from file

I want to create password system in tkinter with notepad as my DB which contains the data in my working directory but when I insert data in the entry fields I receive an error login failed.Have created the txt file but it seems the function can't read from the file.Any suggestion on how to do this.
import tkinter as tk
import sys
from tkinter import messagebox
now = open("passdoc.txt","w+")
now.write("user\n")
now.write("python3")
now.close()
def login_in():
with open("passdoc.txt") as f:
new = f.readlines()
name = new[0].rstrip()
password = new[1].rstrip()
if entry1.get() == new[0] in passdoc.txt and entry2.get() == new[1] in
passdoc.txt:
root.deiconify()
log.destroy()
else:
messagebox.showerror("error","login Failed")
def close():
log.destroy() #Removes toplevel window
root.destroy() #Removes root window
sys.exit() #Ends the script
root=tk.Tk()
log = tk.Toplevel() #
root.geometry("350x350")
log.geometry("200x200")
entry1 = tk.Entry(log) #Username entry
entry2 = tk.Entry(log) #Password entry
button1 = tk.Button(log, text="Login", command=login_in) #Login button
button2 = tk.Button(log, text="Cancel", command=close) #Cancel button
label1 = tk.Label(root, text="tkinter password system")
entry1.pack()
entry2.pack()
button1.pack()
button2.pack()
label1.place(x=30,y=300)
label = tk.Label(root, text="welcome").pack()
root.withdraw()
root.mainloop()
I created this functions too but all seems not to work out for me
def login_in():
with open("passdoc.txt") as f:
new = f.readlines()
name = new[0].rstrip()
password = new[1].rstrip()
if entry1.get() == name in passdoc.txt and entry2.get() == password in
passdoc.txt:
root.deiconify()
log.destroy()
else:
messagebox.showerror("errror","login failed") #error login failed
(corrections)
You have a few things in your code that need some work but the main issue is in your login_in() function.
Your if statement is all wrong. I am not sure why you wrote it the way you did but lets fix it.
Because you defined name = new[0].rstrip() and password = new[1].rstrip()
you can use name and password to verify if the user has enter the correct credentials.
So your if statement should look like this:
if entry1.get() == name and entry2.get() == password:
Your use of in passdoc.txt does not do anything and cannot work because passdoc.txt to python looks like an undefined variable and would fail on the if statement. Remember that you imported all the contents of passdoc.txt as f so you didn't create a variable named passdoc you created one named f for the with open() statement
If you wanted to shorten your code a little you could remove name and password variables and just write the if statement with new
So your login_in() function could look like either this:
def login_in():
with open("passdoc.txt") as f:
new = f.readlines()
name = new[0].rstrip()
password = new[1].rstrip()
if entry1.get() == name and entry2.get() == password:
root.deiconify()
log.destroy()
else:
messagebox.showerror("error","login Failed")
Or this:
def login_in():
with open("passdoc.txt") as f:
new = f.readlines()
if entry1.get() == new[0].rstrip() and entry2.get() == new[1].rstrip():
root.deiconify()
log.destroy()
else:
messagebox.showerror("error","login Failed")

Categories