client code:
import socket
import threading
from tkinter import *
from tkinter import messagebox
PORT = 5000
SERVER = "127.0.0.1"
ADDRESS = (SERVER, PORT)
FORMAT = "utf-8"
BUFFER = 1024
global e1
global e2
global login
global signup
global screen
global window
global listbox
global username
global text_cons
global msg
global entry_msg
global users
global chat
global select_button
global refresh_button
# Create a new client socket
# and connect to the server
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDRESS)
username = ''
def login_screen():
global username
username = e1.get()
password = e2.get()
client.send(('LOGIN ' + username + ' ' + password).encode(FORMAT))
response = client.recv(BUFFER).decode(FORMAT)
if username == '' or password == '':
messagebox.showinfo('', 'must type info')
elif 'INCORRECT' in response:
messagebox.showinfo('', 'username or password incorrect')
elif 'LOGGED IN' in response:
messagebox.showinfo('', 'user is already logged in and online from a different device')
else:
# messagebox.showinfo('', 'signup successful')
go_ahead()
def handle_login():
global login
global e1
global e2
screen.destroy()
# login window
login = Toplevel(bg='#c0ded4')
# set the title
login.title("Login")
login.resizable(width=False,
height=False)
login.configure(width=300,
height=200)
Label(login, bg='#c0ded4', text='username', font='Helvetica 10 bold').place(x=10, y=10)
Label(login, bg='#c0ded4', text='password', font='Helvetica 10 bold').place(x=10, y=40)
e1 = Entry(login)
e1.place(x=140, y=10)
e2 = Entry(login)
e2.place(x=140, y=40)
e2.config(show='*')
Button(login, text='login', font='Helvetica 10 bold', command=login_screen, height=3,
width=13, activebackground='#39a78e', bg='#c0dec5').place(relx=0.5, rely=0.6)
# Button(signup, text='go back', command=login_or_signup(), height=3, width=13, activebackground='#c0dec5',
# bg='#cadec0').place(relx=0.2, rely=0.6)
login.mainloop()
def handle_signup():
global signup
global e1
global e2
screen.destroy()
# login window
signup = Toplevel(bg='#c0ded4')
# set the title
signup.title("signup")
signup.resizable(width=False,
height=False)
signup.configure(width=300,
height=200)
Label(signup, text='new username', font='Helvetica 10 bold', bg='#c0ded4').place(x=10, y=10)
Label(signup, text='new password', font='Helvetica 10 bold', bg='#c0ded4').place(x=10, y=38)
e1 = Entry(signup)
e1.place(x=140, y=10)
e2 = Entry(signup)
e2.place(x=140, y=40)
e2.config(show='*')
Button(signup, text='signup', font='Helvetica 10 bold', command=signup_screen, height=3, width=13,
activebackground='#cadec0', bg='#c0dec5') \
.place(relx=0.3, rely=0.5)
# Button(signup, text='go back', command=login_or_signup(), height=3, width=13, activebackground='#c0dec5',
# bg='#cadec0').place(relx=0.2, rely=0.6)
signup.mainloop()
def signup_screen():
global username
username = e1.get()
password = e2.get()
if ' ' in username or ' ' in password:
messagebox.showinfo('', 'username and password have to be without spaces')
else:
client.send(('SIGNUP ' + username + ' ' + password).encode(FORMAT))
response = client.recv(BUFFER).decode(FORMAT)
if username == '' or password == '':
messagebox.showinfo('', 'must type info')
elif 'USERNAME EXISTS' in response:
messagebox.showinfo('', 'username already exists, try again')
else:
# messagebox.showinfo('', 'signup successful')
go_ahead()
def login_or_signup():
global screen
global login
global signup
try:
signup.destroy()
except:
try:
login.destroy()
except:
print('ready')
# login window
screen = Toplevel(bg='#c0dec5')
# set the title
screen.title("login or signup")
screen.resizable(width=False,
height=False)
screen.configure(width=500,
height=400)
Button(screen, text='LOG IN', font="Helvetica 15 bold", command=handle_login, height=12,
width=14, activebackground='#a69fcc', bg='#c5c0de').place(relx=0.1, rely=0.1)
Button(screen, text='SIGN UP', font="Helvetica 15 bold", command=handle_signup, height=12,
width=14, activebackground='#cca69f', bg='#dec5c0').place(relx=0.5, rely=0.1)
screen.mainloop()
def go_ahead():
global username
try:
login.destroy() # destroy the login window as we've already logged in successfully
except:
signup.destroy()
show_users()
# layout(username)
def back_to_users():
global window
global users
global select_button
global refresh_button
client.send('STOP'.encode(FORMAT))
window.withdraw() # hide chat window again
select_button
refresh_button
# show_users()
# users.deiconify()
# users.destroy()
def show_users():
global listbox
global username
global users
global select_button
global refresh_button
print('entered show users function')
users = Toplevel(bg='#c0dec5')
# set the title
users.title(username + 's contact list')
users.resizable(width=False,
height=False)
users.configure(width=500,
height=400)
print('yas indeed')
message = client.recv(BUFFER).decode(FORMAT)
show = Label(users, text=message, font='Helvetica 10 bold', bg='#c0dec5') # show how many unread texts there are
show.place(x=20, y=30)
show.pack()
show = Label(users, text='select user to text', font='Helvetica 10', bg='#c0dec5') # output message
show.place(relx=0.2, rely=0.4)
show.pack()
client.send('UNREAD MSGS RECEIVED'.encode(FORMAT))
names = client.recv(BUFFER).decode(FORMAT)
listbox = Listbox(users)
# listbox.pack(side=LEFT, fill=BOTH)
listbox.pack(padx=60, pady=50, expand=YES, fill="both")
scrollbar = Scrollbar(users)
scrollbar.place(relheight=1, relx=0.93)
names = names.split(' ') # list of clients names
for name in names:
listbox.insert(END, name)
listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=listbox.yview)
# btn = Button(users, text='SELECT', command=)
select_button = Button(users, text='select', font='Helvetica 10 bold', command=selected_item, height=2, width=6,
bg='#d8c7d6').place(relx=0.38, rely=0.85) # select button
refresh_button = Button(users, text='refresh', font='Helvetica 10 bold', command=append_to_listbox, height=1,
width=8,
bg='#d3cdd2').place(relx=0.1, rely=0.16) # refresh #cadec0button
users.mainloop()
def append_to_listbox():
# we go here when the refresh button is pressed meaning we need to refresh users list
global listbox
client.send('REFRESH'.encode(FORMAT))
listbox.delete(0, END) # delete all items in the listbox
names = client.recv(BUFFER).decode(FORMAT)
while 'to chat' in names: # to screen the server's message of a new user having connected to the system
names = client.recv(BUFFER).decode(FORMAT)
names = names.split(' ') # list of clients names
for name in names:
listbox.insert(END, name)
def selected_item():
# find the user that our client has selected so that we can bring our client to their chat
global username
global listbox
selected = ''
if listbox.curselection(): # if an option has been selected
for i in listbox.curselection():
selected = listbox.get(i)
print(selected)
if selected == username: # if user wants to text self
messagebox.showinfo('', "can't text yourself")
else:
client.send(selected.encode(FORMAT)) # we send the server the selected user
message = client.recv(BUFFER).decode(FORMAT)
if 'exists!' in message: # if user exists then we go on the chat window
client.send('good'.encode(FORMAT))
layout('', selected)
elif 'try again' in message: # if user does not exist they get an error messagebox and move back to users
messagebox.showinfo('', 'client does not exist')
else: # if user did not select option
messagebox.showinfo('', "must select option")
# function to receive messages
def receive():
global text_cons
while True:
try:
message = client.recv(BUFFER).decode(FORMAT)
# if the messages from the server is NAME send the client's name
if message == 'NAME':
client.send(username.encode(FORMAT))
elif 'no unread' in message:
messagebox.showinfo('', "no unread messages from user")
else:
# insert messages to text box
text_cons.config(state=NORMAL)
text_cons.insert(END, message + "\n\n")
text_cons.config(state=DISABLED)
text_cons.see(END)
except:
# an error will be printed on the command line or console if there's an error
print("an error occurred")
client.close()
break
def layout(name, selected): # chat_with is the other user that our client is in the chat with
global text_cons
global entry_msg
global msg
global window
# name = name
# to show chat window
# users.destroy()
# users.iconify()
texts = client.recv(BUFFER).decode(FORMAT)
window = Toplevel(bg='#c0dec5')
# window.deiconify()
window.title("CHATROOM")
window.resizable(width=False,
height=False)
window.configure(width=470,
height=550,
bg="#17202A")
label_head = Label(window,
bg="#17202A",
fg="#EAECEE",
text=selected,
font="Helvetica 13 bold",
pady=5)
label_head.place(relwidth=1)
line = Label(window,
width=450,
bg="#ABB2B9")
line.place(relwidth=1,
rely=0.07,
relheight=0.012)
text_cons = Text(window,
width=20,
height=2,
bg="#17202A",
fg="#EAECEE",
font="Helvetica 14",
padx=5,
pady=5)
text_cons.place(relheight=0.745,
relwidth=1,
rely=0.1)
""" who_texted = Label(window,
text=texts,
width=20,
height=2,
bg="#17202A",
fg="#ABB2B9",
font="Helvetica 12",
padx=1,
pady=1)"""
""" who_texted.place(relwidth=1,
relx=0,
rely=0.08)"""
label_bottom = Label(window,
bg="#ABB2B9",
height=80)
label_bottom.place(relwidth=1,
rely=0.825)
entry_msg = Entry(label_bottom,
bg="#2C3E50",
fg="#EAECEE",
font="Helvetica 13")
# place the given widget
# into the gui window
entry_msg.place(relwidth=0.74,
relheight=0.06,
rely=0.008,
relx=0.011)
entry_msg.focus()
# create a Send Button
button_msg = Button(label_bottom,
command=send_button,
text="send",
font="Helvetica 10 bold",
width=20,
bg="#ABB2B9")
button_msg.place(relx=0.77,
rely=0.008,
relheight=0.06,
relwidth=0.22)
# create a Go Back Button
go_back_btn = Button(label_head,
command=back_to_users,
text="go back",
font="Helvetica 10 bold",
width=30,
bg="#ABB2B9")
go_back_btn.place(relx=0.77,
rely=0.08,
relheight=1,
relwidth=0.22)
text_cons.config(cursor="arrow")
# create a scroll bar
scrollbar = Scrollbar(text_cons)
# place the scroll bar
# into the gui window
scrollbar.place(relheight=1, relx=0.974)
scrollbar.config(command=text_cons.yview)
text_cons.config(state=DISABLED)
rcv = threading.Thread(target=receive) # the thread to receive messages
rcv.start()
window.mainloop()
def send_button():
global msg
global entry_msg
print('in send button')
msg = entry_msg.get()
text_cons.config(state=DISABLED)
entry_msg.delete(0, END)
snd = threading.Thread(target=send_message)
snd.start()
def send_message(): # function to send messages
print('in send message')
text_cons.config(state=DISABLED)
while True:
message = f"{username}: {msg}"
client.send(message.encode(FORMAT))
print('message sent')
break
def main():
global chat
chat = Tk()
chat.withdraw() # chat window that's currently hidden
message = client.recv(BUFFER).decode(FORMAT)
if message == 'LOGIN OR SIGNUP':
login_or_signup()
main()
server code:
import socket
import threading
PORT = 5000
SERVER = "0.0.0.0"
ADDRESS = (SERVER, PORT)
FORMAT = "utf-8"
BUFFER = 1024
clients, names = [], []
users_passwords = {} # users[name] = password. username: password
users_messages = {} # username: {texter: the message unread}
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDRESS)
def start_chat():
print("server is working on " + SERVER)
server.listen()
while True:
# accept connections and returns a new connection to the client and the address bound to it
conn, addr = server.accept()
username = handle_authentication(conn) # if user's authentication is wrong they get stuck in this function
broadcast_message(f"{username} is now available to chat!".encode(FORMAT)) # broadcast message
# conn.send('connection successful!'.encode(FORMAT))
thread = threading.Thread(target=handle, args=(conn, addr, username)) # start the handling thread
thread.start()
print(f"active connections {threading.active_count() - 1}") # amount of clients connected to the server
def handle(conn, addr, username):
# this is the function where the threads go - handle single client as thread
print(f"new connection {addr}\r\n")
connected = True
while connected:
print(users_messages)
print(users_passwords)
if username not in users_messages: # if it's not empty
conn.send("you have no unread messages".encode(FORMAT))
else:
conn.send(f"you have unread messages from {len(users_messages[username])} users".encode(FORMAT))
okay = conn.recv(BUFFER) # receive confirmation from client that the messages have been received
conn.send(' '.join(names).encode(FORMAT)) # send client list of names of the other clients
receiver = conn.recv(BUFFER).decode(FORMAT) # name of client that the user would like to text
print(receiver)
select_user_no_loop(conn, username, receiver)
# close the connection
names.remove(username)
clients.remove(conn)
conn.close()
def select_user_no_loop(conn, username, receiver):
while 'REFRESH' in receiver:
print(username + ' asked to refresh users')
conn.send(' '.join(names).encode(FORMAT)) # send client list of names of the other clients
receiver = conn.recv(BUFFER).decode(FORMAT) # name of client that the user would like to text
while receiver not in names:
conn.send('client does not exist. try again'.encode(FORMAT))
receiver = conn.recv(BUFFER).decode(FORMAT) # name of client that the user would like to text
if username in users_messages and receiver in users_messages[username]:
conn.send('client exists!'.encode(FORMAT))
ok = conn.recv(BUFFER).decode(FORMAT)
conn.send(users_messages[username][receiver].encode(FORMAT))
users_messages[username].pop(receiver) # delete user from unread messages because we just read it
else:
conn.send('client exists!'.encode(FORMAT))
ok = conn.recv(BUFFER).decode(FORMAT)
conn.send(f'no unread messages from {receiver}'.encode(FORMAT))
with_user = True
print(f'{receiver} exists')
while with_user:
# print(f'{username} with {receiver}')
message = conn.recv(BUFFER).decode(FORMAT) # this is protocol TCP so the program waits here until input
if message == 'STOP': # if the client wants out of the chat
print(f'{username} asked to stop chat with {receiver}')
with_user = False # so now we go out of the loop and start another chat
else:
conn.send(message.encode(FORMAT))
# print(clients[names.index(receiver)])
clients[names.index(receiver)].send(message.encode(FORMAT)) # we sent the message to both chatters
print(message)
def select_user(conn, username, receiver):
while True:
while 'REFRESH' in receiver:
print(username + ' asked to refresh users')
conn.send(' '.join(names).encode(FORMAT)) # send client list of names of the other clients
receiver = conn.recv(BUFFER).decode(FORMAT) # name of client that the user would like to text
while receiver not in names:
conn.send('client does not exist. try again'.encode(FORMAT))
receiver = conn.recv(BUFFER).decode(FORMAT) # name of client that the user would like to text
if username in users_messages and receiver in users_messages[username]:
conn.send('client exists!'.encode(FORMAT))
ok = conn.recv(BUFFER).decode(FORMAT)
conn.send(users_messages[username][receiver].encode(FORMAT))
users_messages[username].pop(receiver) # delete user from unread messages because we just read it
else:
conn.send('client exists!'.encode(FORMAT))
ok = conn.recv(BUFFER).decode(FORMAT)
conn.send(f'no unread messages from {receiver}'.encode(FORMAT))
with_user = True
print(f'{receiver} exists')
while with_user:
# print(f'{username} with {receiver}')
message = conn.recv(BUFFER).decode(FORMAT) # this is protocol TCP so the program waits here until input
if message == 'STOP': # if the client wants out of the chat
print(f'{username} asked to stop chat with {receiver}')
with_user = False # so now we go out of the loop and start another chat
else:
conn.send(message.encode(FORMAT))
# print(clients[names.index(receiver)])
clients[names.index(receiver)].send(message.encode(FORMAT)) # we sent the message to both chatters
print(message)
def broadcast_message(message):
# send message to all clients.
for client in clients:
client.send(message)
def handle_authentication(conn): # authentication - login or signup
conn.send("LOGIN OR SIGNUP".encode(FORMAT)) # let's see if the user wants to log in or sign up
while True:
response = conn.recv(BUFFER).decode(FORMAT).split(' ')
print(response)
rcv = response[0]
username = response[1]
password = response[2]
if rcv == 'SIGNUP':
users_passwords[username] = password # append new user details to dictionary
break
elif rcv == 'LOGIN':
if username not in users_passwords or not users_passwords[username] == password:
conn.send("INCORRECT".encode(FORMAT))
continue # skip this iteration
elif username in names:
conn.send("ALREADY LOGGED IN".encode(FORMAT))
continue # skip this iteration
else:
break # if we got here then user logged in with correct info.
names.append(username)
clients.append(conn) # append the name and client to the respective list
print(f"name: {username}")
return username
start_chat() # call the method to begin the communication
after signing up as a client, selecting the user you'd like to chat and then pressing the "go back" button in the chat, the window that shows the listbox of clients does not respond. it still exists and it's shown normally, but when pressing any button in the window - the program crashes. no exceptions presented, the program window just crashes. i really don't know why this happens. any help will be very appreciated :
My GUI Login is skipping over the If part of my If Statement, I don't understand what would be wrong, how can I go about fixing this bug? It should be using the If part when the Username and Password are correct but for some reason it doesn't seem to think that it is part of it.
from tkinter import *
root = Tk()
root.title("My Login")
root.geometry("650x650")
frame = Frame(root)
app = Frame(root)
app.grid
l = Label(root, text = "Login",font="Times 30", padx=5, pady=5)
l.grid()
l1 = Label(root, text = "Username:",font="Times 30", padx=5, pady=5)
l1.grid()
l2 = Label(root, text = "Password:",font="Times 30", padx=5, pady=5)
l2.grid()
user = Entry(root)
user.grid( row= 1, column= 2)
user.configure(font = ("Courier", 44))
code = Entry(root)
code.grid( row= 2, column= 2)
code.configure(font = ("Courier", 44))
operator = user.get()
passcode = code.get()
admin = "" #This would be the Username
password = "" #This would be the Password
def enter():
if (operator == admin and passcode == password):
import subprocess
subprocess.Popen("") #This would be a directory to open
else:
l3 = Label(root, text = "check login", font=("Courier", 22))
l3.grid()
b1 = Button(root, text = "Enter", command = enter, font=("Courier", 44))
b1.grid()
root.mainloop()
You can't preassign the values from get(), you have to call those at the moment you need them.
def enter():
if user.get() == admin and code.get() == password:
import subprocess # this belongs at the top of the file
subprocess.Popen("")
else:
l3 = Label(root, text = "check login", font=("Courier", 22))
l3.grid()
I'm trying to make a GUI for a password storage and hashing system, but I have hit a roadblock. I am having 2 buttons, one to log in, and one to make an account. When the login button is clicked, a new tkinter window opens with the login page. however, the login button is supposed to show on the second page, but it doesn't, and I have no clue why. Here is the code for the full system:
import tkinter
from tkinter import*
username = ("Tom")
password = ("test")
usernameguess1 = ("")
passwordguess1 = ("")
def trylogin():
print ("Trying to login...")
if usernameguess.get() == username:
print ("Complete sucsessfull!")
messagebox.showinfo("Sucess ", "Successfully logged in.")
else:
print ("Error: (Incorrect value entered)")
messagebox.showinfo("Error", "Sorry, but your username or password is incorrect. Try again")
def loginpage():
#Gui Formatting
window = tkinter.Tk()
window.resizable(width=FALSE, height=FALSE)
window.title("HasherTest_V0.1 Login")
window.geometry("300x150")
#Username and password boxes
usernametext = tkinter.Label(window, text="Username:")
usernameguess = tkinter.Entry(window)
passwordtext = tkinter.Label(window, text="Password:")
passwordguess = tkinter.Entry(window, show="*")
usernameguess1 = usernameguess
#login button
attemptlogin = tkinter.Button(text="Login", command=trylogin)
usernametext.pack()
usernameguess.pack()
passwordtext.pack()
passwordguess.pack()
attemptlogin.pack()
window.mainloop()
#Gui Formatting (again)
window = tkinter.Tk()
window.resizable(width=FALSE, height=FALSE)
window.title("HasherTest_V0.1")
window.geometry("300x150")
loginbutton = tkinter.Button(text="Login", command=loginpage)
loginbutton.pack()
And here is the code for just the second window on its own. For some reason I have to import tkinter message boxes aswell, or my IDLE errors out.
import tkinter
from tkinter import *
from tkinter import messagebox
username = ("Tom")
password = ("test")
usernameguess1 = ("")
passwordguess1 = ("")
def trylogin():
print ("Trying to login...")
if usernameguess.get() == username:
print ("Complete sucsessfull!")
messagebox.showinfo("Sucess ", "Successfully logged in.")
else:
print ("Error: (Incorrect value entered)")
messagebox.showinfo("Error", "Sorry, but your username or password is incorrect. Try again")
#Gui Formatting
window = tkinter.Tk()
window.resizable(width=FALSE, height=FALSE)
window.title("HasherTest_V0.1 Login")
window.geometry("300x150")
#Username and password boxes
usernametext = tkinter.Label(window, text="Username:")
usernameguess = tkinter.Entry(window)
passwordtext = tkinter.Label(window, text="Password:")
passwordguess = tkinter.Entry(window, show="*")
usernameguess1 = usernameguess
#login button
attemptlogin = tkinter.Button(text="Login", command=trylogin)
usernametext.pack()
usernameguess.pack()
passwordtext.pack()
passwordguess.pack()
attemptlogin.pack()
window.mainloop()
Thanks for your help!
Here. I completely reworked your code, and it works(as far as I can tell).
I completely removed the textvariable and StringVar(). They aren't needed. The reason your code wasn't working is because you check the name of the file "string", but you need to add ".txt" in order to get a perfect equality.
Code:
import tkinter
from tkinter import*
from tkinter import messagebox
username = ("Tom")
password = ("test")
usernameguess1 = ("")
passwordguess1 = ("")
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 ("Trying to login...")
if usernameguess.get() == username:
print ("Complete sucsessfull!")
messagebox.showinfo("Sucess ", "Successfully logged in.")
else:
print ("Error: (Incorrect value entered)")
messagebox.showinfo("Error", "Sorry, but your username or password is incorrect. Try again")
#login button
attemptlogin = tkinter.Button(root, text="Login", command=trylogin)
usernametext.pack()
usernameguess.pack()
passwordtext.pack()
passwordguess.pack()
attemptlogin.pack()
window.mainloop()
#Gui Formatting (again)
window = tkinter.Tk()
window.resizable(width=FALSE, height=FALSE)
window.title("HasherTest_V0.1")
window.geometry("300x150")
loginbutton = tkinter.Button(window, text="Login", command=loginpage)
loginbutton.pack()
window.mainloop()
I also took the liberty to, as #stovfl mentioned, add Toplevel() instances instead of using Tk() multiple times.
Hope this helps!
my program is meant say 'Accessed granted' if i enter the correct username and password, however regardless of what i type, i keep getting 'Invalid login' can someone point out whats wrong? btw dont worry about it the indentation is wrong, it changes when it put code on this site.
from tkinter import *# Ingress all components from Tkinter
import tkinter.messagebox as box
def dialog1():
username=entry1.get()
password = entry2.get()
if (username == 'admin' and password == 'ad121'):#Correct log in details
box.showinfo('info','Access granted')# correct response
else:
box.showinfo('info','Invalid Login')# decline response
def condition():
while condition == (username == 'admin' and password == 'ad121'):
print = label(text('Welcome back admin user!',bg='Light Blue',font='none 14 bold').place(x=0,y=160))
window = Tk()
window.geometry('400x400')# The size of the form window
window.title('Office login system')#title of the form
frame = Frame(window)
mlabel = Label(text='Log in system', bg='Light Blue',font='none 18 bold underline')# The colours and font style and size used for the form title
mlabel.pack()
Label1 = Label(window,text = 'Username:',bg='Light Blue',font='none 14 bold').place(x=0,y=100)
entry2 = Entry(window).place(x=140,y=108)#Size and colour of the text box
entry1 = Entry(window,bd =5)
entry1.pack
Label2 = Label(window,text = 'Password:',bg='Light Blue',font='none 14 bold').place(x=0,y=150)
entry2 = Entry(window).place(x=140,y=155)#Size and colour of the text box
entry2 = Entry(window, bd=5)
entry2.pack
window.configure(background='Orange')
btn = Button(window, text = 'Check Login',command = dialog1)
btn.place(x=150,y=250)
frame.pack(padx =200,pady =190)
window.mainloop()# The code iterates
You are declaring entry2 multiple times in the scope of your script.
I tried this and it works as you expect.
from tkinter import Button, Entry, Tk
import tkinter.messagebox as box
class GUI:
def __init__(self):
self.root = Tk()
self.username_field = Entry(self.root)
self.password_field = Entry(self.root)
self.username_field.insert(0, "Enter Username")
self.password_field.insert(0, "Enter Password")
self.submit = Button(self.root, text="Submit", command=self.login)
self.username_field.pack()
self.password_field.pack()
self.submit.pack()
def login(self):
username = self.username_field.get()
password = self.password_field.get()
print(username, password)
# The while loop
while username == password:
box.showinfo("info", "Username and password must not match!")
break
if(username == "admin" and password == "ad121"):
box.showinfo("info", "Welcome " + username + "!")
else:
box.showinfo("info", "Invalid credentials")
app = GUI()
app.root.mainloop()
This is a simple GUI program to check whether the user entered correct username and password. The problem is that even when inputting the correct username and password i.e admin and secret, it still outputs 'Invalid Login'
This is the code :
from tkinter import *
import tkinter.messagebox as box
def dialog1():
box.showinfo('info','Correct Login')
def dialog2():
box.showinfo('info','Invalid Login')
window = Tk()
window.title('Countries Generation')
frame = Frame(window)
Label1 = Label(window,text = 'Username:')
Label1.pack(padx=15,pady= 5)
entry1 = Entry(window,bd =5)
entry1.pack(padx=15, pady=5)
username = entry1.get()
Label2 = Label(window,text = 'Password: ')
Label2.pack(padx = 15,pady=6)
entry2 = Entry(window, bd=5)
entry2.pack(padx = 15,pady=7)
password = entry2.get()
if (username == 'admin' and password == 'secret'):
btn = Button(frame, text = 'Check Login',command = dialog1)
else:
btn = Button(frame, text ='Check Login', command = dialog2)
btn.pack(side = RIGHT , padx =5)
frame.pack(padx=100,pady = 19)
window.mainloop()
i think you should think about using a class instead of the raw code which you will be having a good control .
Any way i just corrected your logic instead of checking it before button click get the values after button click and then run
after that your code looks something like this
from tkinter import *
import tkinter.messagebox as box
def dialog1():
username=entry1.get()
password = entry2.get()
if (username == 'admin' and password == 'secret'):
box.showinfo('info','Correct Login')
else:
box.showinfo('info','Invalid Login')
window = Tk()
window.title('Countries Generation')
frame = Frame(window)
Label1 = Label(window,text = 'Username:')
Label1.pack(padx=15,pady= 5)
entry1 = Entry(window,bd =5)
entry1.pack(padx=15, pady=5)
Label2 = Label(window,text = 'Password: ')
Label2.pack(padx = 15,pady=6)
entry2 = Entry(window, bd=5)
entry2.pack(padx = 15,pady=7)
btn = Button(frame, text = 'Check Login',command = dialog1)
btn.pack(side = RIGHT , padx =5)
frame.pack(padx=100,pady = 19)
window.mainloop()
hope that help you to understand what wrong with the previous code