Bug in message sending program - python

I am just experimenting on a messaging program which runs on one computer only. Okay, here's the problem: If I login as an user and send a message to another user, even when I login to the message receiving user, no messages are not there(it say no messages). Please help me out. You are also welcome to give your own suggestions and ways to simplify the code.
import Tkinter as tk
import sys
import tkMessageBox
import csv
accounts = dict()
messages = []
messagerec = []
messagesen = []
csvpath = "C:/Users/user1/Desktop/abc.csv"
csvreader = csv.reader(open(csvpath))
for y, z in csvreader:
accounts[y] = z
def GetUser():
user = userid.get()
return user
def GetPass():
password = passid.get()
return password
def SignUp():
def signupgo():
newuser = newuserid.get()
newpass = newpassid.get()
if newuser in accounts:
tkMessageBox.showerror("Username Taken", 'Sorry! The username you have requested has already been taken. Please try another username.' [2])
else:
accounts[newuser] = newpass
tkMessageBox.showinfo("Account Created", 'Congratulations! Your account has been created' [2])
newuserid = tk.StringVar()
newpassid = tk.StringVar()
SignUpWin = tk.Tk()
NewUserLabel = tk.Label(SignUpWin, text="New Username: ").pack()
NewUserInput = tk.Entry(SignUpWin,textvariable=newuserid).pack()
NewPassLabel = tk.Label(SignUpWin, text="New Password: ").pack()
NewPassInput = tk.Entry(SignUpWin, textvariable=newpassid).pack()
CreateAccount = tk.Button(SignUpWin, text="Create Account", command=signupgo).pack()
def logingo():
user = GetUser()
password = GetPass()
if user in accounts:
if accounts[user] == password:
LoggedIn(user)
elif accounts[user] != password:
tkMessageBox.showerror("Wrong Password", 'Try Again! You have entered the wrong password.')
elif user not in accounts:
tkMessageBox.showerror("User not existing", 'Try Again or Create an account! The username you have provided is not existing.')
def LoggedIn(user):
def MessageButtonClick():
if tkMessageBox.askquestion('Compose or Inbox?', 'Do you want to access your inbox(Yes) or compose a new message(No)?') == 'yes':
OpenInbox(user)
else:
MessageSender(user)
The message sending part starts here.
def MessageSender(user):
messagerecvar = tk.StringVar()
messagecontentvar = tk.StringVar()
messagesenderwin = tk.Tk()
messagereclabel = tk.Label(messagesenderwin, text="Receiver:").pack()
messagerecinput = tk.Entry(messagesenderwin, textvariable=messagerecvar).pack()
messagecontentlabel = tk.Label(messagesenderwin, text="Content:").pack()
messagecontentinput = tk.Entry(messagesenderwin, textvariable=messagecontentvar).pack()
messagecontent = messagecontentvar.get()
messagerec = messagerecvar.get()
messagesendgobutton = tk.Button(messagesenderwin, text='Send Message', command=lambda:sendmessagego(messagecontent, user, messagerec)).pack()
def sendmessagego(content, sender, receiver):
messages.append(content)
messageno = len(messages)
messagerec.append(receiver)
messagesen.append(sender)
tkMessageBox.showinfo("Message Sent", 'Your message has been sent.')
def OpenInbox(user):
if 'a' in messagerec:
lenmess = messagerec.index(user)
tkMessageBox.showinfo('Message from '+messagesen[lenmess], 'Message from '+messagesen[lenmess]+': '+messages[lenmess])
elif user not in messagerec:
tkMessageBox.showinfo('No Messages', 'Sorry, no messages were found')
loggedinwin = tk.Tk()
tkMessageBox.showinfo("Welcome", 'Hello, '+user)
HomeLabel = tk.Label(loggedinwin, text="Home").pack()
MessageMenuButton = tk.Button(loggedinwin, text="Messaging", command=MessageButtonClick).pack()
maingui = tk.Tk()
userid = tk.StringVar()
passid = tk.StringVar()
UserEnterLabel = tk.Label(maingui, text="Username: ").pack()
UserInput = tk.Entry(maingui, textvariable=userid).pack()
PassEnterLabel = tk.Label(maingui, text="Password: ").pack()
PassInput = tk.Entry(maingui, textvariable=passid).pack()
LoginGo = tk.Button(maingui, text="Login", command=logingo).pack()
SignUpGo = tk.Button(maingui, text="Sign Up", command=SignUp).pack()
maingui.mainloop()

The first problem is that you're creating more than one instance of Tk. Tkinter isn't designed to work that way, and will yield unexpected results. If you need more than one window you need to create instances of Toplevel

Related

How can I make this login system work? (Tkinter-python)

The user_entry and pass_entry are just input boxes. Menu function just shows a canvas (blue with text). It only works with the last username and password
The text file is just like this:
user1|password1
name1|password2
def login():
global user_entry, pass_entry, password
user = user_entry.get()
with open("Users and passwords.txt", "r") as f:
lines = f.readlines()
for item in lines:
data = item.split("|")
for i in range(0, 2):
if data[i] == user:
password = data[i+1]
check_pass()
def check_pass():
password_v = pass_entry.get()
if password_v == password:
menu()

How to continue the program outside the function?

I'm new to python and got stuck while trying to build a GUI. I can't find a way to extract data from the 'login' function, which would be the new TopLevel window created after the user logs in. Because of that, I have to write the remaining code inside the 'login function', but I have the impression that there must be another way around. I tried making the new top level global, but it returns that the new variable is not defined.
from tkinter import *
from tkinter import messagebox
root = Tk()
login_frame = LabelFrame(root, text = "login info").pack()
user_field = Label(login_frame, text = "user: ")
user_field.grid(row = 0,column = 0)
pass_field = Label(login_frame, text = "pass: ")
pass_field.grid(row = 1, column = 0)
user_input = Entry(login_frame)
user_input.grid(row = 0, column = 1)
pass_input = Entry(login_frame, show = "*")
pass_input.grid(row = 1, column = 1)
def login():
if user_input.get() == "user" and pass_input.get() == "user":
if messagebox.showinfo("blah", "blah") == "ok":
pass_input.delete(0, END)
user_input.delete(0, END)
root.withdraw()
**app = Toplevel()**
else:
messagebox.showerror("blah", "blah")
pass_input.delete(0, END)
user_input.delete(0, END)
login_btn = Button(login_frame, text = "LOGIN")
login_btn.grid(row = 2, column = 0)
exit_btn = Button(login_frame, text = "SAIR")
exit_btn.grid(row = 2, column = 1)
root.mainloop()
Your code is breaking indentation. The lines following the definition of the function must be inside the scope of the function, like this:
def login():
if user_input.get() == "user" and pass_input.get() == "user":
if messagebox.showinfo("blah", "blah") == "ok":
...
Regardless of that, you may return any type of data at the end of a function. Consider exposing your TopLevel app like this:
return TopLevel()

How do I get a tkinter screen that isn't the root to disapere using either the destroy or withdraw fuction?

I have a log and quiz system using tkinter GUI. The gui screen allows for loging in and registering. This infomation is stored on an excel file saved as a csv.
The quiz portion is done on the python shell. What I want to do, is hide both the log in screen and main screen once the user has logged in and then if they choose the option of Logout, by entering 'D'. The main screen then comes back up.
I have been successful in getting rid of the main screen using the .withdraw function and can get it to appear back using, .deconify. But for some reason, I can't get rid of the log in screen.
It is possible that it's just in the wrong place, but I get an Attribute Error, which states 'function' object has no attribute 'withdraw'(I get the same for destroy)
Below is my code. It's not all of it. But the parts I think you'd need to be able to fix it.
def Destroy_menu():
main_screen.withdraw()
Login.withdraw()
def Quiz(quizfile, User):
print(User, quizfile)
global var
NumberList = [1,2,3,4,5,6,7]
Questions = True
score = 0
questions_answered = 0
while Questions == True:
try:
Number = random.choice(NumberList)
NumberList.remove(Number)
File = open(quizfile + ".csv", "r")
for line in File:
details = line.split(",")
ID_Number = int(details[0])
if ID_Number == Number:
Question = (details[1])
print("Question:",Question)
Answer_one = (details[2])
print("A):",Answer_one)
Answer_Two = (details[3])
print("B):",Answer_Two)
Answer_Three = (details[4])
print("C):",Answer_Three)
Correct = (details[8])
var = StringVar()
X = input("Answer (e.g. A): ")
print("\n")
if X == Correct:
print("Correct")
score += 1
print("Score:", score)
questions_answered = questions_answered + 1
else:
print("Incorrect, answer was:",Correct)
print("Score:", score)
print("\n")
questions_answered = questions_answered + 1
except:
File.close()
print("Quiz Completed")
print("Final Score:", score, "/ 7")
input("Press enter to continue")
Questions = False
#Writing to file
file_writer = csv.writer(open(r"E:\NEA\Quiz\Scores.csv","a",newline =""))
file_writer.writerow([User,quizfile,score,"NA"])
Quiz_choice(User)
def Quiz_choice(User):
Destroy_menu()
flag = False
print("\n" * 50)
print("Pick a quiz")
print("English Quiz (A)")
print("Maths Quiz (B)")
print("Science Quiz (C)")
print("Logout(D)")
while flag == False:
opt = input(">>>: ")
opt = opt.upper()
if opt == "A":
quizfile = "English"
Quiz(quizfile,User)
flag = True
elif opt == "B":
quizfile = "Maths"
Quiz(quizfile,User)
flag = True
elif opt == "C":
quizfile = "Science"
Quiz(quizfile,User)
flag = True
elif opt == "D":
print("Goodbye")
main_screen()
main_screen = Tk()
main_screen.deiconify()
else:
print("Invalid input. Please input a letter")
def Login():
global login_screen
Login_screen = Toplevel(main_screen)
Login_screen.title("Log in")
Login_screen.geometry ("400x234")
Label(Login_screen, text = "Please enter details below to login").pack()
Label(Login_screen, text = "").pack()
global Username_verify
global Password_verify
Username_verify = StringVar()
Password_verify = StringVar()
global Username_login_entry
global Password_login_entry
Label(Login_screen, text = "Username").pack()
Username_login_entry = Entry(Login_screen, textvariable = Username_verify)
Username_login_entry.pack()
Label(Login_screen, text = "").pack()
Label(Login_screen , text = "Password").pack()
Password_login_entry = Entry(Login_screen, textvariable = Password_verify, show = '*')
Password_login_entry.pack()
Label(Login_screen, text ="").pack()
Button(Login_screen, text = "Log in", width = 10, height = 20,command = Login_verify).pack()
Thanks in advance, and ask any questions you need to.

How would add multiple logins to this python script

Hey could you help me with this. I would like to add multiple logins to this script, with each login running separate code. For example if you entered
Username: xyz
Password: zyz
It would run A Script saying
# file-input.py
f = open('helloworld.txt','r')
message = f.read()
print(message)
f.close()
And then if you entered
Username: abc
Password: cba
It would Run this script
'''Illustrate input and print.'''
applicant = input("Enter the applicant's name: ")
interviewer = input("Enter the interviewer's name: ")
time = input("Enter the appointment time: ")
print(interviewer, "will interview", applicant, "at", time)
# file-output.py
f = open('helloworld.txt','w')
f.write(interviewer)
f.write(" will Interview ")
f.write( applicant)
f.write(" at ")
f.write( time)
f.close()
Anyway here's the full code:
from tkinter import *
root = Tk()
username = "abc"
password = "cba"
username_entry = Entry(root)
username_entry.pack()
password_entry = Entry(root, show='*')
password_entry.pack()
def trylogin():
if username == username_entry.get() and password == password_entry.get():
'''Illustrate input and print.'''
applicant = input("Enter the applicant's name: ")
interviewer = input("Enter the interviewer's name: ")
time = input("Enter the appointment time: ")
print(interviewer, "will interview", applicant, "at", time)
# file-output.py
f = open('helloworld.txt','w')
f.write(interviewer)
f.write(" will Interview ")
f.write( applicant)
f.write(" at ")
f.write( time)
f.close()
else:
print("Wrong")
button = Button(root, text="Enter", command = trylogin)
button.pack()
root.mainloop()
Thanks For helping
when writing apps with GUI's, in my opinion it is much easier and more efficient to use an Object orientated approach.
For more details on how to implement tkinter applications using OOP please check out my guy Sentdex:
https://www.youtube.com/watch?v=HjNHATw6XgY&list=PLQVvvaa0QuDclKx-QpC9wntnURXVJqLyk
The code below takes userinputs and checks against the details we have set. If a ceratin username and password are enetered then it will run a certain function. At the moment i have only coded for one outcome, which is if the user enter "abc" ...
Code:
from tkinter import *
import tkinter as tk
class Application(Frame):
def __init__ (self, master):
Frame.__init__(self,master)
self.grid()
self.username1 = "abc"
self.password1 = "cba"
username_label = Label(self, text="Username:")
username_label.grid(row=0, column=0)
password_label = Label(self, text="Password:")
password_label.grid(row=1, column=0)
self.username_entry = Entry(self)
self.username_entry.grid(row=0, column=1)
self.password_entry = Entry(self, show='*')
self.password_entry.grid(row=1, column=1)
login = Button(self, text="Login", command= self.tryLogin)
def tryLogin(self):
usernameInput = self.username_entry.get()
passwordInput = self.password_entry.get()
if usernameInput == self.username1 and passwordInput == self.password1:
self.function1()
else:
print("wrong")
# you can add elif username and password equals something else here but i
#suggest using my alternative method explained below using a database.
def function1(self):
print("executing function 1")
window = tk.Tk()
app = Application(window)
window.mainloop()
HOWEVER In my opinion the best way to execute what you are trying to do is to create a databse for your accounts. In thats database you should by default add the accounts with the function that they will execute.
For instance:
create a database (use sqlite3) with fields username, password, function
Then when a user logins in, you can query the database. If the user enters login details which exist then return the functionName for that respective account and execute it.
*check this link out on how to create a login function and database:
https://www.youtube.com/playlist?list=PLBRzFm0BKuhaQyJ37KiI9rg3R3CC6-v9e
I would show you how to do this but you have to do some research now i have pinpointed you to 2 of the best guys and they cover how to do all these things.
Good luck m8!

How to get the string out of a box which a user has inputted into? Tkinter Python

Hello i am making a log in program on tkinter and i am having trouble when using the box widget where the user is able to input a string. i am trying to take that string out and store it in a variable ready for another time but the way i am trying to do it doesn't actually save anything, is there something that im doing wrong?
from tkinter import *
Wsignup = Tk()
Wsignup.title('Sign up')
UserLabel = Label(Wsignup, text = "Please enter your new username: ")
UserLabel.grid(row = 1, column = 1, sticky = E)
UserEntry = Entry(Wsignup)
UserEntry.grid(row = 1, column = 2, sticky = E)
Username = UserEntry.get()
PassLabel = Label(Wsignup, text = "Please enter your new password: ")
PassLabel.grid(row = 2, column = 1, sticky = E)
PassEntry = Entry(Wsignup, show = '*')
PassEntry.grid(row = 2, column = 2, sticky = E)
Password = PassEntry.get()
You are calling get() before the user had a chance to enter something. Add a Button and call get() in a callback function instead:
def callback():
# global Username, Password # if you want to set global variables
Username = UserEntry.get()
Password = PassEntry.get()
print(Username, Password) # or whatever you need to do with them
Button(Wsignup, text="Login", command=callback).grid(row=3,column=1)

Categories