Esempio n. 1
0
class Login:
    def __init__(self):
        self.db = DBhelper()
        self.root = Tk()

        self.root.title("My Login App")

        self.root.configure(background="#BAF10C")

        self.root.minsize(300, 500)
        self.root.maxsize(300, 500)
        self.load_gui()

    def load_gui(self):

        self.clear()

        self.label1 = Label(self.root, text="Tinder", fg="white", bg="#BAF10C")
        self.label1.configure(font=("Times", 30, "bold"))
        self.label1.pack(pady=(10, 10))

        self.label2 = Label(self.root, text="Email:", fg="white", bg="#BAF10C")
        self.label2.configure(font=("Times", 20, "italic"))
        self.label2.pack(pady=(5, 5))

        self.email = Entry(self.root)
        self.email.pack(pady=(0, 10), ipadx=30, ipady=5)

        self.label3 = Label(self.root,
                            text="Password:"******"white",
                            bg="#BAF10C")
        self.label3.configure(font=("Times", 20, "italic"))
        self.label3.pack(pady=(5, 5))

        self.password = Entry(self.root)
        self.password.pack(pady=(0, 10), ipadx=30, ipady=5)

        self.login = Button(self.root,
                            text="Login",
                            bg="white",
                            command=lambda: self.btn_click())
        self.login.pack(pady=(5, 10), ipadx=70, ipady=4)

        self.label4 = Label(self.root,
                            text="Not a member? Sign Up",
                            fg="white",
                            bg="#BAF10C")
        self.label4.configure(font=("Times", 10, "italic"))
        self.label4.pack(pady=(5, 5))

        self.register = Button(self.root,
                               text="Sign Up",
                               bg="white",
                               command=lambda: self.register_gui())
        self.register.pack(pady=(5, 10), ipadx=40, ipady=2)

        self.root.mainloop()

    def register_gui(self):

        self.clear()

        self.label0 = Label(self.root, text="Tinder", fg="white", bg="#BAF10C")
        self.label0.configure(font=("Times", 30, "bold"))
        self.label0.pack(pady=(10, 10))

        self.label1 = Label(self.root, text="Name:", fg="white", bg="#BAF10C")
        self.label1.configure(font=("Times", 20, "italic"))
        self.label1.pack(pady=(5, 5))

        self.name = Entry(self.root)
        self.name.pack(pady=(0, 10), ipadx=30, ipady=5)

        self.label2 = Label(self.root, text="Email:", fg="white", bg="#BAF10C")
        self.label2.configure(font=("Times", 20, "italic"))
        self.label2.pack(pady=(5, 5))

        self.email = Entry(self.root)
        self.email.pack(pady=(0, 10), ipadx=30, ipady=5)

        self.label3 = Label(self.root,
                            text="Password:"******"white",
                            bg="#BAF10C")
        self.label3.configure(font=("Times", 20, "italic"))
        self.label3.pack(pady=(5, 5))

        self.password = Entry(self.root)
        self.password.pack(pady=(0, 10), ipadx=30, ipady=5)

        self.filebtn = Button(self.root,
                              text="Upload Profile Picture",
                              command=lambda: self.upload_file())
        self.filebtn.pack(pady=(5, 5))

        self.filename = Label(self.root)
        self.filename.pack(pady=(5, 5))

        self.register = Button(self.root,
                               text="Sign Up",
                               bg="white",
                               command=lambda: self.reg_submit())
        self.register.pack(pady=(5, 10), ipadx=70, ipady=4)

        self.label4 = Label(self.root,
                            text="Already a member? Login",
                            fg="white",
                            bg="#BAF10C")
        self.label4.configure(font=("Times", 10, "italic"))
        self.label4.pack(pady=(5, 5))

        self.login = Button(self.root,
                            text="Login",
                            bg="white",
                            command=lambda: self.load_gui())
        self.login.pack(pady=(5, 10), ipadx=40, ipady=2)

    def upload_file(self):
        filename = filedialog.askopenfilename(initialdir="/images",
                                              title="Somrhting")
        self.filename.configure(text=filename)

    def clear(self):

        for i in self.root.pack_slaves():
            i.destroy()

    def btn_click(self):
        email = self.email.get()
        password = self.password.get()

        data = self.db.check_login(email, password)
        print(data)

        if len(data) > 0:
            self.clear()
            self.user_id = data[0][0]
            self.user_data = data[0]
            self.load_user_info()
        else:
            messagebox.showerror("Error", "Incorrect Email/Password")

    def load_user_info(self):
        self.main_window(self.user_data)

    def logout(self):
        self.user_id = ''
        self.user_data = ''

        self.load_gui()

    def view_others(self, index=0):
        # Fetch data of all other users
        data = self.db.fetch_others(self.user_id)
        #print(data)
        num = len(data)
        self.main_window(data[index], mode=2, index=index, num=num)

    def navbar(self):
        menu = Menu(self.root)
        self.root.config(menu=menu)
        filemenu = Menu(menu)
        menu.add_cascade(label="Home", menu=filemenu)
        filemenu.add_command(label="My Profile",
                             command=lambda: self.main_window(self.user_data))
        filemenu.add_command(label="Edit Profile",
                             command=lambda: self.edit_profile())
        filemenu.add_command(label="View Profile",
                             command=lambda: self.view_others())
        filemenu.add_command(label="LogOut", command=lambda: self.logout())

        helpmenu = Menu(menu)
        menu.add_cascade(label="Proposals", menu=helpmenu)
        helpmenu.add_command(label="My Proposals",
                             command=lambda: self.view_proposals())
        helpmenu.add_command(label="My Requests",
                             command=lambda: self.view_requests())
        helpmenu.add_command(label="My Matches",
                             command=lambda: self.view_matches())

    def view_requests(self, index=0):
        # Step 1 - fetch data from database
        data = self.db.view_requests(self.user_id)

        # Step 2 - call main_window function
        num = len(data)
        new_data = []
        for i in data:
            new_data.append(i[3:])

        self.main_window(new_data[index], mode=3, index=index, num=num)

    def view_proposals(self, index=0):
        # Step 1 - fetch data from database
        data = self.db.view_proposals(self.user_id)

        # Step 2 - call main_window function
        num = len(data)
        new_data = []
        for i in data:
            new_data.append(i[3:])

        self.main_window(new_data[index], mode=3, index=index, num=num)

    def view_matches(self, index=0):
        # Step 1 - fetch data from database
        data = self.db.view_matches(self.user_id)

        # Step 2 - call main_window function
        num = len(data)
        new_data = []
        for i in data:
            new_data.append(i[3:])

        self.main_window(new_data[index], mode=3, index=index, num=num)

    def main_window(self, data, mode=1, index=None, num=None):

        self.clear()

        self.navbar()

        imageUrl = "images/{}".format(data[8])

        load = Image.open(imageUrl)
        load = load.resize((200, 200), Image.ANTIALIAS)
        render = ImageTk.PhotoImage(load)

        img = Label(image=render)
        img.image = render
        img.pack()

        self.label1 = Label(self.root,
                            text="Name:" + data[1],
                            fg="white",
                            bg="#BAF10C")
        self.label1.configure(font=("Times", 15, "bold"))
        self.label1.pack(pady=(10, 10))

        if len(data[7]) != 0:
            self.label2 = Label(self.root,
                                text="From:" + data[7],
                                fg="white",
                                bg="#BAF10C")
            self.label2.configure(font=("Times", 15, "bold"))
            self.label2.pack(pady=(10, 10))

        if len(data[6]) != 0:
            self.label3 = Label(self.root,
                                text="Not interested in:" + data[6],
                                fg="white",
                                bg="#BAF10C")
            self.label3.configure(font=("Times", 15, "bold"))
            self.label3.pack(pady=(10, 10))

        if len(data[4]) != 0:
            self.label4 = Label(self.root,
                                text="About Me:" + data[4],
                                fg="white",
                                bg="#BAF10C")
            self.label4.configure(font=("Times", 10))
            self.label4.pack(pady=(10, 10))

        if mode == 2:
            frame = Frame(self.root)
            frame.pack()

            if index != 0:
                previous = Button(
                    frame,
                    text="Previous",
                    command=lambda: self.view_others(index=index - 1))
                previous.pack(side='left')

            propose = Button(
                frame,
                text="Propose",
                command=lambda: self.propose(self.user_id, data[0]))
            propose.pack(side='left')

            if index != (num - 1):
                next = Button(
                    frame,
                    text="Next",
                    command=lambda: self.view_others(index=index + 1))
                next.pack(side='left')

        if mode == 3:
            frame = Frame(self.root)
            frame.pack()

            if index != 0:
                previous = Button(
                    frame,
                    text="Previous",
                    command=lambda: self.view_proposals(index=index - 1))
                previous.pack(side='left')

            if index != (num - 1):
                next = Button(
                    frame,
                    text="Next",
                    command=lambda: self.view_proposals(index=index + 1))
                next.pack(side='left')

    def propose(self, romeo_id, juliet_id):

        response = self.db.propose(romeo_id, juliet_id)
        if response == 1:
            messagebox.showinfo(
                "Success", "Proposal sent successfully. Fingers Crossed!")
        elif response == -1:
            messagebox.showerror("Error",
                                 "You have already proposed this user.")
        else:
            messagebox.showerror("Error", "Some error occured")

    def edit_profile(self):

        self.clear()

        self.label0 = Label(self.root,
                            text="Edit Profile",
                            fg="white",
                            bg="#BAF10C")
        self.label0.configure(font=("Times", 30, "bold"))
        self.label0.pack(pady=(10, 10))

        self.label1 = Label(self.root, text="Bio:", fg="white", bg="#BAF10C")
        self.label1.configure(font=("Times", 10, "italic"))
        self.label1.pack(pady=(5, 5))

        self.bio = Entry(self.root)
        self.bio.pack(pady=(0, 10), ipadx=30, ipady=5)

        self.label2 = Label(self.root, text="Age:", fg="white", bg="#BAF10C")
        self.label2.configure(font=("Times", 10, "italic"))
        self.label2.pack(pady=(5, 5))

        self.age = Entry(self.root)
        self.age.pack(pady=(0, 10), ipadx=30, ipady=5)

        self.label3 = Label(self.root,
                            text="Gender:",
                            fg="white",
                            bg="#BAF10C")
        self.label3.configure(font=("Times", 10, "italic"))
        self.label3.pack(pady=(5, 5))

        self.gender = Entry(self.root)
        self.gender.pack(pady=(0, 10), ipadx=30, ipady=5)

        self.label4 = Label(self.root, text="City:", fg="white", bg="#BAF10C")
        self.label4.configure(font=("Times", 10, "italic"))
        self.label4.pack(pady=(5, 5))

        self.city = Entry(self.root)
        self.city.pack(pady=(0, 10), ipadx=30, ipady=5)

        self.edit = Button(self.root,
                           text="Edit Profile",
                           bg="white",
                           command=lambda: self.update_profile())
        self.edit.pack(pady=(5, 10), ipadx=70, ipady=4)

    def update_profile(self):
        bio = self.bio.get()
        age = self.age.get()
        gender = self.gender.get()
        city = self.city.get()

        info = [bio, age, gender, city]

        response = self.db.update_profile(self.user_id, info)

        if response == 1:
            messagebox.showinfo("Success", "Profile Updated")
        else:
            messagebox.showerror("Error", "Some error occured")

    def reg_submit(self):
        name = self.name.get()
        email = self.email.get()
        password = self.password.get()
        filename = self.filename['text'].split('/')[-1]

        resposnse = self.db.insert_user(name, email, password, filename)

        if resposnse == 1:
            shutil.copyfile(
                self.filename['text'],
                "C:\\Users\\Atulya\\PycharmProjects\\finder\\images\\" +
                filename)
            messagebox.showinfo("Registration Successful",
                                "You may login now!")
        else:
            messagebox.showerror("Error", "Database Error")
Esempio n. 2
0
class quiz:

    # constructor for quiz class

    def __init__(self):
        self.total_correct_answer = 0
        self.root = Tk()
        self.db = DBhelper()  #connecting DBhelper class of dbhelper.py
        self.root.title("Quizzyy")  #Title of gui

        self.root.configure(bg="#ceff0a")

        self.myFont = font.Font(family='Comic Sans MS', size=10, weight='bold')

        self.root.minsize(500, 700)  #minimum size of gui
        self.root.maxsize(500, 700)  #maximum size of gui
        self.login_page()

        self.root.mainloop(
        )  #to keep gui on screen untill interfered be any keyboard input or mouse

    # function to clear the gui

    def clear(self):

        for i in self.root.pack_slaves():
            i.destroy()

    # function for displaying login page

    def login_page(self):

        self.clear()

        self.root.configure(bg="#ceff0a")

        self.root.minsize(500, 700)
        self.root.maxsize(500, 700)

        self.label1 = Label(self.root,
                            text="Quizzyy",
                            fg="black",
                            bg="#ceff0a")
        self.label1.configure(font=("Comic Sans MS", 30, "bold"))
        self.label1.pack(pady=(10, 5))

        self.alabel3 = Label(self.root,
                             text="-" * 70,
                             fg="black",
                             bg="#ceff0a")
        self.alabel3.configure(font=("Comic Sans MS", 10))
        self.alabel3.pack(pady=(5, 10), fill=X)

        self.elabel = Label(self.root, text="Email", fg="black", bg="#ceff0a")
        self.elabel.configure(font=("Comic Sans MS", 20, "italic"))
        self.elabel.pack(pady=(40, 5))

        self.email = Entry(self.root)
        self.email.pack(pady=(0, 15), ipadx=40, ipady=4)

        self.plabel = Label(self.root,
                            text="Password",
                            fg="black",
                            bg="#ceff0a")
        self.plabel.configure(font=("Comic Sans MS", 20, "italic"))
        self.plabel.pack(pady=(10, 5))

        self.password = Entry(self.root)
        self.password.pack(pady=(0, 10), ipadx=40, ipady=5)

        #login button for logging in of user when pressed
        # calls login_btn function

        self.login = Button(self.root,
                            text="Login",
                            fg="white",
                            bg="#7d9c00",
                            command=lambda: self.login_btn())
        self.login['font'] = self.myFont
        self.login.pack(pady=(5, 25), ipadx=70, ipady=4)

        self.label2 = Label(self.root,
                            text="Not a member? Sign Up",
                            fg="black",
                            bg="#ceff0a")
        self.label2.configure(font=("Comic Sans MS", 20, "italic"))
        self.label2.pack(pady=(25, 10))

        # registration button for registering new user when pressed
        # calls register_btn function

        self.register = Button(self.root,
                               text="Sign Up",
                               fg="white",
                               bg="#7d9c00",
                               command=lambda: self.register_btn())
        self.register['font'] = self.myFont
        self.register.pack(pady=(5, 10), ipadx=70, ipady=4)

    #functon called whenever login button is pressed
    # extract email and password inserted by user
    # and check it in the database
    # if credentials are correct user get logged in
    #otherwise user have to enter his/her details again

    def login_btn(self):
        email = self.email.get()
        password = self.password.get()

        data = self.db.check_login(email, password)

        if len(data) > 0:
            self.clear()
            self.player_id = data[0][0]
            self.player_data = data[0]
            self.load_home()

        else:
            messagebox.showerror("Error", "Incorrext Email/password")

    #function gets called whenever Sign Up button is pressed
    #loads the register page
    #user can register if he/she has not yet registered

    def register_btn(self):
        self.root.minsize(500, 800)
        self.root.maxsize(500, 800)
        self.clear()

        self.label1 = Label(self.root,
                            text="Quizzyy",
                            fg="black",
                            bg="#ceff0a")
        self.label1.configure(font=("Comic Sans MS", 30, "bold"))
        self.label1.pack(pady=(10, 5))

        self.alabel3 = Label(self.root,
                             text="-" * 70,
                             fg="black",
                             bg="#ceff0a")
        self.alabel3.configure(font=("Comic Sans MS", 10))
        self.alabel3.pack(pady=(5, 10), fill=X)

        self.nlabel = Label(self.root,
                            text="Full Name : ",
                            fg="black",
                            bg="#ceff0a")
        self.nlabel.configure(font=("Comic Sans MS", 20, "italic"))
        self.nlabel.pack(pady=(15, 5))

        self.name = Entry(self.root)
        self.name.pack(pady=(0, 5), ipadx=40, ipady=5)

        self.elabel = Label(self.root,
                            text="Email : ",
                            fg="black",
                            bg="#ceff0a")
        self.elabel.configure(font=("Comic Sans MS", 20, "italic"))
        self.elabel.pack(pady=(10, 5))

        self.email = Entry(self.root)
        self.email.pack(pady=(0, 5), ipadx=40, ipady=5)

        self.plabel = Label(self.root,
                            text="Password : "******"black",
                            bg="#ceff0a")
        self.plabel.configure(font=("Comic Sans MS", 20, "italic"))
        self.plabel.pack(pady=(10, 5))

        self.password = Entry(self.root)
        self.password.pack(pady=(0, 5), ipadx=40, ipady=5)

        self.cplabel = Label(self.root,
                             text="Confirm Password :"******"black",
                             bg="#ceff0a")
        self.cplabel.configure(font=("Comic Sans MS", 20, "italic"))
        self.cplabel.pack(pady=(10, 5))

        self.cpassword = Entry(self.root)
        self.cpassword.pack(pady=(0, 5), ipadx=40, ipady=5)

        self.unlabel = Label(
            self.root,
            text="Username \n (You won't be able to change it later)  :",
            fg="black",
            bg="#ceff0a")
        self.unlabel.configure(font=("Comic Sans MS", 18, "italic"))
        self.unlabel.pack(pady=(10, 5))

        self.username = Entry(self.root)
        self.username.pack(pady=(0, 5), ipadx=40, ipady=5)

        #register button for sending new user's data to database for entry
        # calls confirm_register function when pressed

        self.register = Button(self.root,
                               text="Sign Up ",
                               fg="white",
                               bg="#7d9c00",
                               command=lambda: self.confirm_register())
        self.register['font'] = self.myFont
        self.register.pack(pady=(5, 5), ipadx=70, ipady=4)

        self.label2 = Label(self.root,
                            text="Already a member? Login",
                            fg="black",
                            bg="#ceff0a")
        self.label2.configure(font=("Comic Sans MS", 20, "italic"))
        self.label2.pack(pady=(20, 5))

        #Login button to go back to login page
        #calls login_page function when pressed

        self.login = Button(self.root,
                            text="Login",
                            fg="white",
                            bg="#7d9c00",
                            command=lambda: self.login_page())
        self.login['font'] = self.myFont
        self.login.pack(pady=(5, 10), ipadx=70, ipady=4)

    #gets called whenever register button of register page is pressed
    #extract the data entered by user and adds it into the database
    #check whether user has entered correct or not if not then user have to enter correct input

    def confirm_register(self):
        name = self.name.get()
        if len(name) <= 0:
            messagebox.showerror("Error!!!", "Name cannot be empty")

        else:
            email = self.email.get()

            if len(email) <= 0:
                messagebox.showerror("Error!!!", "Email cannot be empty")

            else:
                password = self.password.get()
                if len(password) <= 0:
                    messagebox.showerror("Error!!!",
                                         "Password cannot be empty")

                else:
                    cpassword = self.cpassword.get()

                    if len(cpassword) <= 0:
                        messagebox.showerror(
                            "Error!!!", "Confirm password cannot be empty")

                    else:
                        username = self.username.get()

                        if len(username) <= 0:
                            messagebox.showerror("Error!!!",
                                                 "Username cannot be empty")

                        else:
                            emresponse = self.db.check_email(email)

                            if emresponse == 0:
                                messagebox.showerror("Error",
                                                     "Email already taken")

                            else:

                                if password != cpassword:
                                    messagebox.showerror(
                                        "Error",
                                        "Password & confirm password does not match"
                                    )

                                else:

                                    if len(username) > 10:
                                        messagebox.showerror(
                                            "Error!!!",
                                            "Length of username cannot exceed 10 characters"
                                        )

                                    else:
                                        uresponse = self.db.check_username(
                                            username)

                                        if uresponse == 0:
                                            messagebox.showerror(
                                                "Error!!!",
                                                "Username already taken")

                                        else:
                                            response = self.db.insert_user(
                                                name, email, password,
                                                username)

                                            if response == 1:
                                                #shows a success popup if registration is successful
                                                # and goes back to login page
                                                messagebox.showinfo(
                                                    "Registration Successful",
                                                    "You may login now")
                                                self.login_page()

                                            else:
                                                #shows error if any error occurred while registration
                                                messagebox.showerror(
                                                    "Error!!!",
                                                    "Database error")

    #gets called if user credential is correct and login button is pressed
    #This is basically homepage of every user
    #There are total 5 options i.e., New Game, Leaderboard, Help, Change Password and logout

    def load_home(self):
        self.clear()
        self.root.configure(bg="#00FF00")

        self.root.minsize(500, 700)
        self.root.maxsize(500, 700)

        self.label1 = Label(self.root,
                            text="Quizzyy",
                            fg="black",
                            bg="#00FF00")
        self.label1.configure(font=("Comic Sans MS", 40, "bold"))
        self.label1.pack(pady=(30, 5))

        self.alabel3 = Label(self.root,
                             text="-" * 70,
                             fg="black",
                             bg="#00FF00")
        self.alabel3.configure(font=("Comic Sans MS", 10))
        self.alabel3.pack(pady=(5, 10), fill=X)

        self.label2 = Label(self.root,
                            text="M A I N   M E N U",
                            fg="black",
                            bg="#00FF00")
        self.label2.configure(font=("Comic Sans MS", 20, "bold"))
        self.label2.pack(pady=(30, 10))

        self.label2 = Label(self.root,
                            text="Welcome : " + self.player_data[2],
                            fg="black",
                            bg="#00FF00")
        self.label2.configure(font=("Comic Sans MS", 12, "bold"))
        self.label2.pack(pady=(10, 5))

        #Newgame button to start a new game
        #calls level function when pressed

        self.new_game = Button(self.root,
                               text="New Game",
                               fg="white",
                               bg="#008000",
                               command=lambda: self.level())
        self.new_game['font'] = self.myFont
        self.new_game.pack(pady=(50, 10), ipadx=80, ipady=4)

        # Leaderboard button to see leaderboard
        # calls leaderboard function when pressed

        self.leaders = Button(self.root,
                              text="Leaderboards",
                              fg="white",
                              bg="#008000",
                              command=lambda: self.leaderboard())
        self.leaders['font'] = self.myFont
        self.leaders.pack(pady=(20, 10), ipadx=70, ipady=4)

        # Help button to see help
        # calls help function when pressed

        self.helpp = Button(self.root,
                            text="Help",
                            fg="white",
                            bg="#008000",
                            command=lambda: self.help())
        self.helpp['font'] = self.myFont
        self.helpp.pack(pady=(20, 10), ipadx=99, ipady=4)

        #Change password for changing password
        #call take_new_password when pressed

        self.change = Button(self.root,
                             text="Change Password",
                             fg="white",
                             bg="#008000",
                             command=lambda: self.take_new_password())
        self.change['font'] = self.myFont
        self.change.pack(pady=(20, 10), ipadx=60, ipady=4)

        # Logout button for logging out
        # goes back to login page when pressed

        self.logOut = Button(self.root,
                             text="Log Out",
                             fg="white",
                             bg="#008000",
                             command=lambda: self.logout())
        self.logOut['font'] = self.myFont
        self.logOut.pack(pady=(20, 10), ipadx=88, ipady=4)

    #functions gets called whenever new game is pressed on homepage
    #This function is for selecting the quiz level
    #There are total 3 difficulties i.e., Easy, Normal and Hard
    # There is also an extra button to go back to main menu(home page)

    def level(self):
        self.clear()

        self.root.minsize(500, 650)
        self.root.maxsize(500, 650)

        self.label1 = Label(self.root,
                            text=" Quizzyy ",
                            fg="black",
                            bg="#00FF00")
        self.label1.configure(font=("Comic Sans MS", 40, "bold"))
        self.label1.pack(pady=(25, 5))

        self.alabel3 = Label(self.root,
                             text="-" * 70,
                             fg="black",
                             bg="#00FF00")
        self.alabel3.configure(font=("Comic Sans MS", 10))
        self.alabel3.pack(pady=(5, 10), fill=X)

        self.label2 = Label(self.root,
                            text="N E W   G A M E",
                            fg="black",
                            bg="#00FF00")
        self.label2.configure(font=("Comic Sans MS", 20, "bold"))
        self.label2.pack(pady=(30, 10))

        self.label3 = Label(self.root,
                            text="Select Difficulty",
                            fg="black",
                            bg="#00FF00")
        self.label3.configure(font=("Comic Sans MS", 15, "bold"))
        self.label3.pack(pady=(5, 10))

        #to set difficulty level easy
        #calls fetch_question to fetch easy level questions

        self.easy = Button(self.root,
                           text="Easy",
                           fg="white",
                           bg="#008000",
                           command=lambda: self.fetch_question(mode=0))
        self.easy['font'] = self.myFont
        self.easy.pack(pady=(30, 10), ipadx=80, ipady=4)

        # to set difficulty level normal
        # calls fetch_question to fetch normal level questions

        self.normal = Button(self.root,
                             text="Normal",
                             fg="white",
                             bg="#008000",
                             command=lambda: self.fetch_question(mode=1))
        self.normal['font'] = self.myFont
        self.normal.pack(pady=(20, 10), ipadx=73, ipady=4)

        # to set difficulty level hard
        # calls fetch_question to fetch hard level questions

        self.hard = Button(self.root,
                           text="Hard",
                           fg="white",
                           bg="#008000",
                           command=lambda: self.fetch_question(mode=2))
        self.hard['font'] = self.myFont
        self.hard.pack(pady=(20, 10), ipadx=80, ipady=4)

        #to go back to main menu

        self.back = Button(self.root,
                           text="Main Menu",
                           fg="white",
                           bg="#008000",
                           command=lambda: self.load_home())
        self.back['font'] = self.myFont
        self.back.pack(pady=(50, 10), ipadx=63, ipady=4)

    #This function gets called after selecting level
    # It fetches question from API according to difficulty level selected by user
    # The fetched data is in the form of json or in simple words key value pairs just like dictionary of python

    def fetch_question(self, mode):

        #to fetch questions of easy level using api

        if mode == 0:
            url = "https://opentdb.com/api.php?amount=10&difficulty=easy&type=multiple"
            response = requests.get(url)
            self.response = response.json()
            self.data = self.response['results']
            self.extract_question(mode=mode)

        #to fetch questions of normal level using api

        if mode == 1:
            url = "https://opentdb.com/api.php?amount=10&difficulty=medium&type=multiple"
            response = requests.get(url)
            self.response = response.json()
            self.data = self.response['results']
            self.extract_question(mode=mode)

        #to fetch questions of hard level using api
        if mode == 2:
            url = "https://opentdb.com/api.php?amount=10&difficulty=hard&type=multiple"
            response = requests.get(url)
            self.response = response.json()
            self.data = self.response['results']
            self.extract_question(mode=mode)

    #This functions gets called after successfully fetching 10 questions from api
    #it extract a single question from the data fetched by fetch_questions function every time it gets called
    #stores the extracted question and its option in a list
    #and stores correct aanswer in other variable

    def extract_question(self, mode, index=0):
        self.clear()
        question = ['', '', '', '']
        options = []
        question.insert(0, self.data[index]['question'])

        #to generate random location for storing correct option
        num = random.randint(1, 4)

        #storing correct answer at randum index generated above
        question[num] = self.data[index]['correct_answer']

        #to remember location od=f right answer
        if num == 1:
            self.correct_answer = 'A'
            self.correct_number = 1

        if num == 2:
            self.correct_answer = 'B'
            self.correct_number = 2

        if num == 3:
            self.correct_answer = 'C'
            self.correct_number = 3

        if num == 4:
            self.correct_answer = 'D'
            self.correct_number = 4

        options.append(num)

        i = 1
        j = 0

        while i != 4:

            #generating randum locations for wrong options

            num = random.randint(1, 4)
            if num not in options:

                #storing wrong options at randum indexes generated above

                question.pop(num)
                question.insert(num, self.data[index]['incorrect_answers'][j])
                options.append(num)
                i += 1
                j += 1

        #to replace special characters number with special characters

        question[0] = question[0].replace('&quot;', '"')
        question[0] = question[0].replace('&#039;', "'")
        question[0] = question[0].replace('&amp;', '&')
        question[0] = question[0].replace('&e', 'é')
        question[0] = question[0].replace('acute;', '-')

        question[1] = question[1].replace('&quot;', '"')
        question[1] = question[1].replace('&#039;', "'")
        question[1] = question[1].replace('&amp;', '&')
        question[1] = question[1].replace('&e', '&')
        question[1] = question[1].replace('acute;', '-')

        question[2] = question[2].replace('&quot;', '"')
        question[2] = question[2].replace('&#039;', "'")
        question[2] = question[2].replace('&amp;', '&')
        question[2] = question[2].replace('&e', 'é')
        question[2] = question[2].replace('acute;', '-')

        question[3] = question[3].replace('&quot;', '"')
        question[3] = question[3].replace('&#039;', "'")
        question[3] = question[3].replace('&amp;', '&')
        question[3] = question[3].replace('&e', 'é')
        question[3] = question[3].replace('acute;', '-')

        question[4] = question[4].replace('&quot;', '"')
        question[4] = question[4].replace('&#039;', "'")
        question[4] = question[4].replace('&amp;', '&')
        question[4] = question[4].replace('&e', 'é')
        question[4] = question[4].replace('acute;', '-')

        self.display_question(question, index=index, mode=mode)

    #This function is for displaying the extracted question and its options to user
    #User have to select an option and press next for  next question
    #Gets called after fetch_question function everytime
    #There is also a button to go back to main menu if user doesn't want to continue playing

    def display_question(self, question, index, mode):

        self.clear()

        self.root.minsize(1500, 700)
        self.root.maxsize(1500, 700)

        self.label1 = Label(self.root,
                            text=" Quizzyy ",
                            fg="black",
                            bg="#00FF00")
        self.label1.configure(font=("Comic Sans MS", 40, "bold"))
        self.label1.pack(pady=(25, 5), fill=X)

        self.label3 = Label(self.root,
                            text="-" * 100,
                            fg="black",
                            bg="#00FF00")
        self.label3.configure(font=("Comic Sans MS", 10))
        self.label3.pack(pady=(5, 10), fill=X)

        self.qlabel = Label(self.root,
                            text="Q" + str(index + 1) + ". " + question[0],
                            fg='black',
                            bg="#00FF00")
        self.qlabel.configure(font=("Times New Roman", 18, "bold"))
        self.qlabel.pack(pady=(30, 10), fill=X)

        self.alabel1 = Label(self.root,
                             text="A.    " + question[1],
                             fg='black',
                             bg="#00FF00")
        self.alabel1.configure(font=("Times New Roman", 15, "italic"))
        self.alabel1.pack(pady=(20, 10), padx=(50, 50), fill=X)

        self.alabel2 = Label(self.root,
                             text="B.    " + question[2],
                             fg='black',
                             bg="#00FF00")
        self.alabel2.configure(font=("Times New Roman", 15, "italic"))
        self.alabel2.pack(pady=(10, 10), padx=(50, 50), fill=X)

        self.alabel3 = Label(self.root,
                             text="C.    " + question[3],
                             fg='black',
                             bg="#00FF00")
        self.alabel3.configure(font=("Times New Roman", 15, "italic"))
        self.alabel3.pack(pady=(10, 10), padx=(50, 50), fill=X)

        self.alabel4 = Label(self.root,
                             text="D.    " + question[4],
                             fg='black',
                             bg="#00FF00")
        self.alabel4.configure(font=("Times New Roman", 15, "italic"))
        self.alabel4.pack(pady=(10, 10), padx=(50, 50), fill=X)

        self.label2 = Label(self.root,
                            text="Enter Your Answer:",
                            fg='black',
                            bg='#00ff00')
        self.label2.configure(font=("Comic Sans MS", 15))
        #self.label2.place(x=50,y=570)
        self.label1.pack(pady=(30, 10), padx=(50, 50), fill=X)

        # to remove default value of answer label when user click on entry box

        def in_click(event):
            if self.answer.get() == self.answer.default_value:
                event.widget.delete(0, END)

        # to insert default value of answer label back in it if nothing is entered
        # and user go out of scope from that entry box

        def out_click(event):
            if len(self.answer.get()) == 0:
                event.widget.delete(0, END)
                event.widget.insert(0, self.answer.default_value)

        #Entry box for answer insertion
        self.answer = Entry(self.root)
        self.answer.default_value = 'Enter Your Answer'
        self.answer.insert(0, self.answer.default_value)
        self.answer.bind("<FocusIn>", in_click)
        self.answer.bind("<FocusOut>", out_click)
        self.answer.pack(pady=(0, 15), ipadx=40, ipady=4)

        # to get next question if index not equals to 9 i.e., question not equal to 0
        #calls check_answer function

        if index != 9:
            next = Button(
                self.root,
                text="Next ->",
                fg="white",
                bg="#008000",
                command=lambda: self.check_answers(index=index + 1, mode=mode))
            next['font'] = self.myFont
            next.pack(pady=(5, 10), ipadx=30, ipady=4)

        #to submit answers and to show user's score in that game
        #calls check_answer function
        if index == 9:
            next = Button(
                self.root,
                text="Submit Answers",
                fg="white",
                bg="#008000",
                command=lambda: self.check_answers(index=index + 1, mode=mode))
            next['font'] = self.myFont
            next.pack(pady=(5, 10), ipadx=30, ipady=4)

        # to go back to main menu
        self.back = Button(self.root,
                           text="Main Menu",
                           fg="white",
                           bg="#008000",
                           command=lambda: self.confirm())
        self.back['font'] = self.myFont
        self.back.pack(pady=(50, 10), ipadx=40, ipady=4)

    # To confirm whether user really want to exit the game or not
    #gets called whenever MainMenu button of game page is pressed
    #asks whether user really wants to exit
    #if yes his progress doesn't get saved
    #otherwise user stays on game page

    def confirm(self):
        choice = messagebox.askquestion(
            "Exit", "Are you sure, Your progress won't be saved")
        if choice == 'yes':
            self.load_home()

    #this function is for checking the answer given by user of a particular question is correct or not
    #If the answer is correct the total score of user gets increased by 1
    # and calls the extract_question function to extract next question
    #THis function gets called only when question number is less than 10

    def check_answers(self, index, mode):

        answer = self.answer.get()
        if index != 10:

            # to check answer of every question and increase score by 1 if answer is correct
            #gets called only when question number ranges between 1 to 10 or
            #index ranges between 0 to 9

            if answer.upper(
            ) == self.correct_answer or answer == self.correct_number:
                self.total_correct_answer += 1

        else:
            # to check highscor after game ends and update if current game score is greater than high score
            self.check_highscore(mode, self.total_correct_answer)

        if index != 10:
            # to extract next question
            self.extract_question(mode, index)

    #This function gets called after the quiz is over
    #it is for checking whether the score obtain by user in this quiz is higher than his/her  high score of this mode
    #if it is higher than the previous high score his his high score get updated to new value

    def check_highscore(self, mode, correct):

        high = self.db.check_highscore(self.player_id, mode)
        if correct > high:

            #updating highscore

            response = self.db.update_highscore(self.player_id, mode, correct)

            if response == 1:
                print("Highscore Updated")

        else:
            print("Score less than high score")

        #for showing total score of user in current game

        self.show_score(correct)

    #This function gets called after the quiz is over
    #it is for showing the total score of the user in the quiz
    #it has two buttons leaderboard to see the leaderboard and main menu to go back to main menu

    def show_score(self, correct):

        self.clear()

        self.root.minsize(450, 650)
        self.root.maxsize(450, 650)

        self.label1 = Label(self.root,
                            text="Quizzyy",
                            fg="black",
                            bg="#00FF00")
        self.label1.configure(font=("Comic Sans MS", 40, "bold"))
        self.label1.pack(pady=(25, 5))

        self.alabel3 = Label(
            self.root,
            text=
            "-------------------------------------------------------------------------------------------",
            fg="black",
            bg="#00FF00")
        self.alabel3.configure(font=("Comic Sans MS", 10))
        self.alabel3.pack(pady=(5, 10), fill=X)

        self.label2 = Label(self.root,
                            text="R E S U L T ",
                            fg="black",
                            bg="#00FF00")
        self.label2.configure(font=("Comic Sans MS", 20, "bold"))
        self.label2.pack(pady=(30, 10))

        if correct > 5:

            self.label3 = Label(self.root,
                                text="C O N G R A T S",
                                fg="black",
                                bg="#00FF00")
            self.label3.configure(font=("Comic Sans MS", 18, "bold"))
            self.label3.pack(pady=(30, 10))

        self.label4 = Label(self.root,
                            text="You got" + str(correct) + "/10 correct",
                            fg="black",
                            bg="#00FF00")
        self.label4.configure(font=("Comic Sans MS", 15, "bold"))
        self.label4.pack(pady=(20, 10))

        #Leaderboard button to see leaderboard after game completion if user wants to

        self.leaders = Button(self.root,
                              text="Leaderboards",
                              fg="white",
                              bg="#008000",
                              command=lambda: self.leaderboard())
        self.leaders['font'] = self.myFont
        self.leaders.pack(pady=(50, 10), ipadx=70, ipady=4)

        #main menu button to go to main menu
        self.back = Button(self.root,
                           text="Main Menu",
                           fg="white",
                           bg="#008000",
                           command=lambda: self.load_home())
        self.back['font'] = self.myFont
        self.back.pack(pady=(20, 10), ipadx=63, ipady=4)

    #this function gets called whenever leaderboard button is pressed
    #user is asked which difficulty level leaderboard he want to see
    #after getting input from user as easy, normal or hard
    #fetch_leaderboard function gets called

    def leaderboard(self):
        self.clear()

        self.root.minsize(450, 650)
        self.root.maxsize(450, 650)

        self.label1 = Label(self.root,
                            text="Quizzyy",
                            fg="black",
                            bg="#00FF00")
        self.label1.configure(font=("Comic Sans MS", 40, "bold"))
        self.label1.pack(pady=(25, 10))

        self.alabel3 = Label(self.root,
                             text="-" * 70,
                             fg="black",
                             bg="#00FF00")
        self.alabel3.configure(font=("Comic Sans MS", 10))
        self.alabel3.pack(pady=(5, 10), fill=X)

        self.label2 = Label(self.root,
                            text="L E A D E R B O A R D",
                            fg="black",
                            bg="#00FF00")
        self.label2.configure(font=("Comic Sans MS", 20, "bold"))
        self.label2.pack(pady=(30, 10))

        self.label3 = Label(self.root,
                            text="Select Difficulty",
                            fg="black",
                            bg="#00FF00")
        self.label3.configure(font=("Comic Sans MS", 15, "bold"))
        self.label3.pack(pady=(5, 10))

        #for easy level scoreboard

        self.easy = Button(self.root,
                           text="Easy",
                           fg="white",
                           bg="#008000",
                           command=lambda: self.fetch_leaderboard(mode=0))
        self.easy['font'] = self.myFont
        self.easy.pack(pady=(30, 10), ipadx=80, ipady=4)

        #for normal level scoreboard

        self.normal = Button(self.root,
                             text="Normal",
                             fg="white",
                             bg="#008000",
                             command=lambda: self.fetch_leaderboard(mode=1))
        self.normal['font'] = self.myFont
        self.normal.pack(pady=(20, 10), ipadx=73, ipady=4)

        #for hard level scoreboard

        self.hard = Button(self.root,
                           text="Hard",
                           fg="white",
                           bg="#008000",
                           command=lambda: self.fetch_leaderboard(mode=2))
        self.hard['font'] = self.myFont
        self.hard.pack(pady=(20, 10), ipadx=80, ipady=4)

        #to go back to main menu

        self.back = Button(self.root,
                           text="Main Menu",
                           fg="white",
                           bg="#008000",
                           command=lambda: self.load_home())
        self.back['font'] = self.myFont
        self.back.pack(pady=(50, 10), ipadx=64, ipady=4)

    #this function gets called after selecting the level of leaderboard user want to see
    #it fetches leaderboard of that particular difficulty from database
    #and calls show_leaderboard function to show the leaderboard

    def fetch_leaderboard(self, mode):
        leader_data = self.db.fetch_leaderboard(mode)
        self.show_leaderboard(leader_data)

    #This function gets called by fetch_leaderboard function
    #and shows tha data fetched by that function i.e., leaderboard on window
    #there is a back button to go back to level selection for leaderboard

    def show_leaderboard(self, data):
        self.clear()

        self.root.minsize(600, 700)
        self.root.maxsize(600, 700)

        self.label1 = Label(self.root,
                            text="Quizzyy",
                            fg="black",
                            bg="#00FF00")
        self.label1.configure(font=("Comic Sans MS", 40, "bold"))
        self.label1.pack(pady=(25, 10))

        self.alabel3 = Label(self.root,
                             text="-" * 85,
                             fg="black",
                             bg="#00FF00")
        self.alabel3.configure(font=("Comic Sans MS", 10))
        self.alabel3.pack(pady=(5, 10), fill=X)

        self.label2 = Label(self.root,
                            text="L E A D E R B O A R D",
                            fg="black",
                            bg="#00FF00")
        self.label2.configure(font=("Comic Sans MS", 20, "bold"))
        self.label2.pack(pady=(30, 10))

        self.label2 = Label(self.root,
                            text="Rank \t      Username    \t   Score",
                            fg="black",
                            bg="#00FF00")
        self.label2.configure(font=("Comic Sans MS", 20, "bold"))
        self.label2.pack(pady=(15, 10))

        if len(data) > 5:
            lim = 5

        else:
            lim = len(data)

        for i in range(lim):
            self.label01 = Label(self.root,
                                 text=str(i + 1) + ".      \t    " +
                                 data[i][0] + "    \t    " + str(data[i][1]),
                                 fg="black",
                                 bg="#00FF00")
            self.label01.configure(font=("Footlight MT", 20, "italic"))
            self.label01.pack(pady=(15, 10))

        self.back = Button(self.root,
                           text="<- Back",
                           fg="white",
                           bg="#008000",
                           command=lambda: self.leaderboard())
        self.back['font'] = self.myFont
        self.back.pack(pady=(50, 10), ipadx=70, ipady=4)

    #This function gets called whenever help button is pressed on main menu or homepage
    #This shows details about this app and how to play it

    def help(self):
        self.clear()

        self.root.minsize(950, 900)
        self.root.maxsize(950, 900)

        self.label1 = Label(self.root,
                            text="Quizzyy",
                            fg="black",
                            bg="#00FF00")
        self.label1.configure(font=("Comic Sans MS", 40, "bold"))
        self.label1.pack(pady=(25, 10))

        self.alabel3 = Label(self.root,
                             text="-" * 80,
                             fg="black",
                             bg="#00FF00")
        self.alabel3.configure(font=("Comic Sans MS", 10))
        self.alabel3.pack(pady=(5, 10), fill=X)

        self.label2 = Label(self.root,
                            text="H E L P",
                            fg="black",
                            bg="#00FF00")
        self.label2.configure(font=("Comic Sans MS", 20, "bold"))
        self.label2.pack(pady=(15, 10))

        self.help_label = Label(
            self.root,
            text=
            "1. You have to login using your email and password.                                                         \n\n 2. If registered you will get redirected to home page otherwise you have to register.     \n\n 3. On home page you can check leaderboard, start a new game or change your password \n on starting new game you will get 3 options based on difficulty i.e., Easy, Normal, Hard.\n\n 4.Select difficulty and your game starts.                                                               "
            "            \n\n 5. Questions are multiple choice you will get 4 options from which you have to select one.\n\n 6. There are total of 10 questions.                                                                                     "
            "\n\n7. On answering all the questions you will see your score and can check leaderboard also. "
            "\n\n This game is developed be ATULYA KUMAR as project on Python programmin language",
            fg="black",
            bg="#00FF00")
        self.help_label.configure(font=("Comic Sans MS", 15))
        self.help_label.pack(pady=(5, 10))

        self.back = Button(self.root,
                           text="<- Back",
                           fg="white",
                           bg="#008000",
                           command=lambda: self.load_home())
        self.back['font'] = self.myFont
        self.back.pack(pady=(30, 10), ipadx=70, ipady=4)

    #This function is for password updation
    #gets called whenever change password button is pressed on main menu/homepage
    #asks for users old password, new password and to confirm new password

    def take_new_password(self):
        self.clear()

        self.label1 = Label(self.root,
                            text="Quizzyy",
                            fg="black",
                            bg="#00FF00")
        self.label1.configure(font=("Comic Sans MS", 40, "bold"))
        self.label1.pack(pady=(25, 10))

        self.alabel3 = Label(self.root,
                             text="-" * 70,
                             fg="black",
                             bg="#00FF00")
        self.alabel3.configure(font=("Comic Sans MS", 10))
        self.alabel3.pack(pady=(5, 10), fill=X)

        self.label2 = Label(self.root,
                            text="Enter Old Password",
                            fg="black",
                            bg="#00FF00")
        self.label2.configure(font=("Comic Sans MS", 20, "italic"))
        self.label2.pack(pady=(15, 10))

        self.old_password = Entry(self.root)
        self.old_password.pack(pady=(0, 5), ipadx=40, ipady=5)

        self.label3 = Label(self.root,
                            text="Enter New Password",
                            fg="black",
                            bg="#00FF00")
        self.label3.configure(font=("Comic Sans MS", 20, "italic"))
        self.label3.pack(pady=(15, 10))

        self.new_password = Entry(self.root)
        self.new_password.pack(pady=(0, 5), ipadx=40, ipady=5)

        self.label4 = Label(self.root,
                            text="Confirm New Password",
                            fg="black",
                            bg="#00FF00")
        self.label4.configure(font=("Comic Sans MS", 20, "italic"))
        self.label4.pack(pady=(15, 10))

        self.con_new_password = Entry(self.root)
        self.con_new_password.pack(pady=(0, 5), ipadx=40, ipady=5)

        self.next = Button(self.root,
                           text="Change Password",
                           fg="white",
                           bg="#008000",
                           command=lambda: self.update())
        self.next['font'] = self.myFont
        self.next.pack(pady=(50, 10), ipadx=55, ipady=4)

        self.back = Button(self.root,
                           text="Main Menu",
                           fg="white",
                           bg="#008000",
                           command=lambda: self.load_home())
        self.back['font'] = self.myFont
        self.back.pack(pady=(30, 10), ipadx=75, ipady=4)

    #extract old password new password and confirm new password from take_new_password
    #if old password is correct and new password and confirm new password matches
    #users password gets updated to new password

    def update(self):
        player = self.player_id
        password = self.old_password.get()
        new_password = self.new_password.get()
        con_new_password = self.con_new_password.get()

        #to check password length is not empty
        if len(new_password) <= 0:
            messagebox.showerror("Error", "Password cannot be empty")

        else:
            if new_password != con_new_password:
                messagebox.showerror(
                    "Error", "New Password and Confirm Password doesn't match")

            else:
                #updation of password
                response = self.db.update_password(player, password,
                                                   new_password)

                if response == -1:
                    messagebox.showerror("Error",
                                         "Old Password does not match")

                elif response == 1:
                    messagebox.showinfo("Updated",
                                        "Password Updated Successfully")
                    self.load_home()

                else:
                    messagebox.showerror("Error", "Some error occurred")

    #This functions gets called when logout button is pressed on main menu/homepage
    #function clears all the data extractes from database of users which gets extracted at the time of login
    #calls login_page function to load login page for looging in of other user

    def logout(self):
        response = messagebox.askquestion("Confirm",
                                          "Are you sure you want to logout?")
        if response == 'yes':

            #deletion of user data before logging out which is fetched from database at time of login

            self.player_id = ''
            self.player_data = []

            #going back to login page

            self.login_page()
Esempio n. 3
0
class Login:
    def __init__(self):
        self.db = DBhelper()
        self.root = Tk()

        self.root.title("My login App")

        self.root.configure(background="#043CFA")

        self.root.minsize(400, 500)
        self.root.maxsize(400, 500)

        self.load_gui()

    def load_gui(self):

        self.clear()

        self.label1 = Label(self.root, text="Tinder", fg="white", bg="#043CFA")
        self.label1.configure(font=("Times", 30, "bold"))
        self.label1.pack(pady=(10, 10))

        self.label2 = Label(self.root, text="Email:", fg="white", bg="#043CFA")
        self.label2.configure(font=("Times", 20, "italic"))
        self.label2.pack(pady=(5, 5))

        self.emailinput = Entry(self.root)
        self.emailinput.pack(pady=(0, 10), ipadx=40, ipady=5)

        self.label3 = Label(self.root,
                            text="Password:"******"white",
                            bg="#043CFA")
        self.label3.configure(font=("Times", 20, "italic"))
        self.label3.pack(pady=(5, 5))

        self.password = Entry(self.root)
        self.password.pack(pady=(0, 10), ipadx=40, ipady=5)

        self.login = Button(self.root,
                            text="Login",
                            bg="white",
                            command=lambda: self.btn_click())
        self.login.configure(font=("Times", 15))
        self.login.pack(pady=(8, 10), ipadx=70, ipady=4)

        self.label4 = Label(self.root,
                            text="Not a member?",
                            fg="white",
                            bg="#043CFA")
        self.label4.configure(font=("Times", 15, "italic"))
        self.label4.pack(pady=(5, 5))

        self.register = Button(self.root,
                               text="Sign up",
                               bg="white",
                               command=lambda: self.register_gui())
        self.register.configure(font=("Times", 10))
        self.register.pack(pady=(8, 10), ipadx=30, ipady=4)

        self.root.mainloop()

    def register_gui(self):
        self.clear()

        self.label0 = Label(self.root, text="Tinder", fg="white", bg="#043CFA")
        self.label0.configure(font=("Times", 30, "bold"))
        self.label0.pack(pady=(5, 0))

        self.label1 = Label(self.root, text="Name", fg="white", bg="#043CFA")
        self.label1.configure(font=("Times", 20, "italic"))
        self.label1.pack(pady=(5, 0))

        self.name = Entry(self.root)
        self.name.pack(pady=(0, 2), ipadx=40, ipady=5)

        self.label2 = Label(self.root, text="Email:", fg="white", bg="#043CFA")
        self.label2.configure(font=("Times", 20, "italic"))
        self.label2.pack(pady=(5, 0))

        self.emailinput = Entry(self.root)
        self.emailinput.pack(pady=(0, 2), ipadx=40, ipady=5)

        self.label3 = Label(self.root,
                            text="Password:"******"white",
                            bg="#043CFA")
        self.label3.configure(font=("Times", 20, "italic"))
        self.label3.pack(pady=(5, 0))

        self.password = Entry(self.root)
        self.password.pack(pady=(0, 2), ipadx=40, ipady=5)

        self.filebtn = Button(self.root,
                              text="Upload Pic",
                              bg="white",
                              command=lambda: self.upload_file())
        self.filebtn.pack(pady=(5, 0), ipadx=40, ipady=4)

        self.filename = Label(self.root)
        self.filename.pack(pady=(5, 5), ipadx=40, ipady=4)

        self.register = Button(self.root,
                               text="Sign Up",
                               bg="white",
                               command=lambda: self.reg_submit())
        self.register.pack(pady=(5, 5), ipadx=70, ipady=4)

        self.label4 = Label(self.root,
                            text="Already a member?",
                            fg="white",
                            bg="#043CFA")
        self.label4.configure(font=("Times", 15, "italic"))
        self.label4.pack(pady=(10, 2))

        self.signin = Button(self.root,
                             text="Sign In",
                             bg="white",
                             command=lambda: self.load_gui())
        self.signin.configure(font=("Times", 10))
        self.signin.pack(pady=(5, 10), ipadx=30, ipady=4)

    def upload_file(self):
        filename = filedialog.askopenfilename(initialdir="/images",
                                              title="Somrhting")
        self.filename.configure(text=filename)

    def clear(self):

        for i in self.root.pack_slaves():
            i.destroy()

    def btn_click(self):
        email = self.emailinput.get()
        password = self.password.get()
        #print(email,password)

        data = self.db.check_login(email, password)

        if len(data) > 0:
            self.clear()
            self.user_id = data[0][0]
            self.user_data = data[0]
            self.load_user_info()
            #messagebox.showinfo("Login successful","You may proceed!")
        else:
            messagebox.showerror("Error", "Incorrect Email/password")

    def load_user_info(self):
        self.main_window(self.user_data)

    def logout(self):
        self.user_id = ""
        self.user_data = ""
        self.navbar(mode=0)
        self.load_gui()

    def viewothers(self, index=0):
        data = self.db.fetch_others(self.user_id)
        #print(data)
        num = len(data)
        self.main_window(data[index], mode=2, index=index, num=num)

    def navbar(self, mode=None):

        menu = Menu(self.root)
        self.root.config(menu=menu)
        filemenu = Menu(menu)
        helpmenu = Menu(menu)
        if mode == 1:

            menu.add_cascade(label="Home", menu=filemenu)
            filemenu.add_command(
                label="My Profile",
                command=lambda: self.main_window(self.user_data))
            filemenu.add_command(label="Edit Profile",
                                 command=lambda: self.editprofile())
            filemenu.add_command(label="View Profile",
                                 command=lambda: self.viewothers())
            filemenu.add_command(label="LogOut", command=lambda: self.logout())

            menu.add_cascade(label="Proposals", menu=helpmenu)
            helpmenu.add_command(label="My Proposals",
                                 command=lambda: self.view_proposals())
            helpmenu.add_command(label="My Requests",
                                 command=lambda: self.view_requests())
            helpmenu.add_command(label="My Matches",
                                 command=lambda: self.view_matches())
        else:
            filemenu.destroy()
            helpmenu.destroy()

    def view_matches(self, index=0):
        data = self.db.view_matches(self.user_id)

        num = len(data)
        if num == 0:
            messagebox.showerror("Error", "Opps you have matches yet")
        else:
            new_data = []
            for i in data:
                new_data.append(i[3:])

            self.main_window(new_data[index], mode=3, index=index, num=num)

    def view_proposals(self, index=0):
        #step 1- fetch data from database
        data = self.db.view_proposals(self.user_id)

        num = len(data)
        if num == 0:
            messagebox.showerror("Error", "Opps you haven't propose any one")
        else:
            new_data = []
            for i in data:
                new_data.append(i[3:])

            self.main_window(new_data[index], mode=3, index=index, num=num)

    def view_requests(self, index=0):
        #step 1- fetch data from database
        data = self.db.reqst_proposals(self.user_id)

        num = len(data)
        if num == 0:
            messagebox.showerror("Error",
                                 "Opps you don't have any proposal yet")
        else:
            new_data = []
            for i in data:
                new_data.append(i[3:])

            self.main_window(new_data[index], mode=4, index=index, num=num)

    def main_window(self, data, mode=1, index=None, num=None):

        self.clear()

        self.navbar(mode=1)

        imageUrl = "images/{}".format(data[8])

        load = Image.open(imageUrl)
        load = load.resize((150, 150), Image.ANTIALIAS)
        render = ImageTk.PhotoImage(load)

        img = Label(image=render)
        img.image = render
        img.pack()

        self.label1 = Label(self.root,
                            text="Name: " + " " + data[1],
                            fg="white",
                            bg="#043CFA")
        self.label1.configure(font=("Times", 20, "bold"))
        self.label1.pack(pady=(10, 10))

        if len(data[7]) != 0:
            self.label2 = Label(self.root,
                                text="From:  " + data[7],
                                fg="white",
                                bg="#043CFA")
            self.label2.configure(font=("Times", 15, "bold"))
            self.label2.pack(pady=(10, 10))

        if len(data[6]) != 0:
            self.label3 = Label(self.root,
                                text="Gender:  " + data[6],
                                fg="white",
                                bg="#043CFA")
            self.label3.configure(font=("Times", 15, "bold"))
            self.label3.pack(pady=(10, 10))

        if len(str(data[5])) != 0:
            self.label4 = Label(self.root,
                                text="Age:  " + str(data[5]),
                                fg="white",
                                bg="#043CFA")
            self.label4.configure(font=("Times", 15, "bold"))
            self.label4.pack(pady=(10, 10))

        if len(data[4]) != 0:
            self.label5 = Label(self.root,
                                text="About Me:  " + data[4],
                                fg="white",
                                bg="#043CFA")
            self.label5.configure(font=("Times", 15, "bold"))
            self.label5.pack(pady=(10, 10))

        if mode == 2:
            frame = Frame(self.root)
            frame.pack()

            if index != 0:
                previous = Button(frame,
                                  text="Previous",
                                  command=lambda: self.viewothers(index - 1))
                previous.pack(side='left')

            propose = Button(
                frame,
                text="Propose",
                command=lambda: self.propose(self.user_id, data[0]))
            propose.pack(side='left')

            if index != (num - 1):
                next = Button(frame,
                              text="Next",
                              command=lambda: self.viewothers(index + 1))
                next.pack(side='left')

        if mode == 3:
            frame = Frame(self.root)
            frame.pack()

            if index != 0:
                previous = Button(
                    frame,
                    text="Previous",
                    command=lambda: self.view_proposals(index - 1))
                previous.pack(side='left')

            if index != (num - 1):
                next = Button(frame,
                              text="Next",
                              command=lambda: self.view_proposals(index + 1))
                next.pack(side='left')
        if mode == 4:
            frame = Frame(self.root)
            frame.pack()

            if index != 0:
                previous = Button(
                    frame,
                    text="Previous",
                    command=lambda: self.view_requests(index - 1))
                previous.pack(side='left')

            if index != (num - 1):
                next = Button(frame,
                              text="Next",
                              command=lambda: self.view_requests(index + 1))
                next.pack(side='left')

    def propose(self, romeo_id, juliet_id):
        response = self.db.propose(romeo_id, juliet_id)
        if response == 1:
            messagebox.showinfo("Success", "Your proposal is successful")
        elif response == -1:
            messagebox.showerror("Error", "You have already proposed")
        else:
            messagebox.showerror("Error", "Some error occured")

    def editprofile(self):

        self.clear()

        self.label0 = Label(self.root,
                            text="Edit Profile",
                            fg="white",
                            bg="#043CFA")
        self.label0.configure(font=("Times", 15, "bold"))
        self.label0.pack(pady=(5, 10))

        self.label1 = Label(self.root, text="Bio", fg="white", bg="#043CFA")
        self.label1.configure(font=("Times", 15, "italic"))
        self.label1.pack(pady=(2, 2))

        self.bio = Entry(self.root)
        self.bio.pack(pady=(0, 5), ipadx=40, ipady=5)

        self.label2 = Label(self.root, text="Age", fg="white", bg="#043CFA")
        self.label2.configure(font=("Times", 15, "italic"))
        self.label2.pack(pady=(2, 2))

        self.age = Entry(self.root)
        self.age.pack(pady=(0, 5), ipadx=40, ipady=5)

        self.label3 = Label(self.root, text="Gender", fg="white", bg="#043CFA")
        self.label3.configure(font=("Times", 15, "italic"))
        self.label3.pack(pady=(2, 2))

        self.gender = Entry(self.root)
        self.gender.pack(pady=(0, 5), ipadx=40, ipady=5)

        self.label3 = Label(self.root, text="City", fg="white", bg="#043CFA")
        self.label3.configure(font=("Times", 15, "italic"))
        self.label3.pack(pady=(2, 2))

        self.city = Entry(self.root)
        self.city.pack(pady=(0, 5), ipadx=40, ipady=5)

        self.filebtn = Button(self.root,
                              text="Change Pic",
                              bg="white",
                              command=lambda: self.upload_file())
        self.filebtn.pack(pady=(5, 0), ipadx=40, ipady=4)

        self.filename = Label(self.root)
        self.filename.pack(pady=(5, 10), ipadx=40, ipady=4)

        self.edit = Button(self.root,
                           text="Edit profile",
                           bg="white",
                           command=lambda: self.updateprofile())
        self.edit.pack(pady=(5, 10), ipadx=50, ipady=4)

    def updateprofile(self):

        bio = self.bio.get()
        age = self.age.get()
        gender = self.gender.get()
        city = self.city.get()
        filename = self.filename['text'].split('/')[-1]

        info = [bio, age, gender, city, filename]

        response = self.db.update_profile(self.user_id, info)

        if response == 1:
            shutil.copyfile(
                self.filename['text'],
                "C:\\Users\\SHIBAM\\PycharmProjects\\Finder\\images\\" +
                filename)
            messagebox.showinfo(
                "Success",
                "Profile Updated To see the updates Logout and then login")
        else:
            messagebox.showerror("Error", "Some error occured")

    def reg_submit(self):
        name = self.name.get()
        email = self.emailinput.get()
        password = self.password.get()
        filename = self.filename['text'].split('/')[-1]

        response = self.db.insert_user(name, email, password, filename)

        if response == 1:

            shutil.copyfile(
                self.filename['text'],
                "C:\\Users\\SHIBAM\\PycharmProjects\\Finder\\images\\" +
                filename)
            messagebox.showinfo("Registration successful",
                                "You may login proceed!")
        else:
            messagebox.showerror("Database Error",
                                 " Fill the ragistration form properly")
Esempio n. 4
0
class Login:
    def __init__(self):
        self.db = DBhelper()  #loading the database
        self.root = Tk()  #root is created once
        self.root.title(
            "My Login App")  #slaves of the root are created more than once
        self.root.configure(background="red")
        self.root.minsize(300, 500)
        self.root.maxsize(300, 500)
        self.load_gui()

    def load_gui(self):
        self.clear()
        self.label1 = Label(self.root, text="Tinder", fg="white", bg="red")
        self.label1.configure(font=("Times", 30, "bold"))
        self.label1.pack(
            pady=(10, 10))  # puts lbel on gui#three line forming label

        self.label2 = Label(self.root, text="Email:", fg="white",
                            bg="#7D05FC")  #fg=foreground bg=background
        self.label2.configure(font=("Times", 20, "italic"))
        self.label2.pack(pady=(5, 5))  # padding in y direction

        self.email = Entry(self.root)
        self.email.pack(pady=(0, 10), ipadx=30,
                        ipady=5)  # to take a text input
        # setting margin x=0,y=10,.....again setting x,y

        self.label3 = Label(self.root,
                            text="Password:"******"white",
                            bg="#7D05FC")
        self.label3.configure(font=("Times", 20, "italic"))
        self.label3.pack(pady=(5, 5))  # padding in y direction

        self.password = Entry(self.root)
        self.password.pack(pady=(0, 10), ipadx=30, ipady=5)

        # adding button
        self.login = Button(self.root,
                            text="Login",
                            bg="white",
                            command=lambda: self.btn_click())
        #aftter clicking button command is getting storred
        self.login.pack(pady=(3, 10), ipadx=35,
                        ipady=0.5)  # 1 is for increasing the y height

        self.label4 = Label(self.root,
                            text="Not a member?sign up",
                            fg="white",
                            bg="#7D05FC")
        self.label4.configure(font=("Times", 15, "italic"))
        self.label4.pack(pady=(5, 5))

        self.register = Button(self.root,
                               text="sign up",
                               bg="white",
                               command=lambda: self.register_gui())
        # aftter clicking button command is getting storred
        self.register.pack(pady=(5, 10), ipadx=35, ipady=1)

        self.root.mainloop()  #same like getch

    def register_gui(self):  #for signing up purpose
        self.clear()

        self.label0 = Label(self.root, text="Tinder", fg="white", bg="red")
        self.label0.configure(font=("Times", 30, "bold"))
        self.label0.pack(
            pady=(10, 10))  # puts lbel on gui#three line forming label

        self.label1 = Label(self.root, text="Nane:", fg="white",
                            bg="#7D05FC")  # fg=foreground bg=background
        self.label1.configure(font=("Times", 20, "italic"))
        self.label1.pack(pady=(5, 5))  # padding in y direction

        self.name = Entry(self.root)
        self.name.pack(pady=(0, 10), ipadx=30, ipady=5)  # to take a text input
        # setting margin x=0,y=10,.....again setting x,y

        self.label2 = Label(self.root, text="Email:", fg="white",
                            bg="#7D05FC")  # fg=foreground bg=background
        self.label2.configure(font=("Times", 20, "italic"))
        self.label2.pack(pady=(5, 5))  # padding in y direction

        self.email = Entry(self.root)
        self.email.pack(pady=(0, 10), ipadx=30, ipady=5)

        self.label3 = Label(self.root,
                            text="Password:"******"white",
                            bg="#7D05FC")
        self.label3.configure(font=("Times", 20, "italic"))
        self.label3.pack(pady=(5, 5))  # padding in y direction

        self.password = Entry(self.root)
        self.password.pack(pady=(0, 10), ipadx=30, ipady=5)

        self.filebtn = Button(self.root,
                              text="Upload dp",
                              command=lambda: self.upload_file())
        self.filebtn.pack(pady=(5, 5))

        self.filename = Label(self.root)
        self.filename.pack(pady=(5, 5))

        # adding button
        self.register = Button(self.root,
                               text="sign up",
                               bg="white",
                               command=lambda: self.reg_submit())
        # aftter clicking button command is getting storred
        self.register.pack(pady=(3, 10), ipadx=55,
                           ipady=0.5)  # 1 is for increasing the y height

        self.label4 = Label(self.root,
                            text="Already a member?sign up",
                            fg="white",
                            bg="#7D05FC")
        self.label4.configure(font=("Times", 15, "italic"))
        self.label4.pack(pady=(5, 5))

        self.login = Button(self.root,
                            text="login",
                            bg="white",
                            command=lambda: self.load_gui())
        # aftter clicking button command is getting storred
        self.login.pack(pady=(5, 10), ipadx=35, ipady=1)

    def upload_file(self):
        filename = filedialog.askopenfilename(initialdir="/images",
                                              title="Something")
        self.filename.configure(text=filename)

    def clear(self):
        for i in self.root.pack_slaves():
            i.destroy()

    def btn_click(self):
        email = self.email.get()
        password = self.password.get()

        data = self.db.check_login(email, password)

        if len(data) > 0:  #not empty string
            #messagebox.showinfo("login successful","you may procced now!")
            self.clear()
            self.user_id = data[0][0]  #to fetch 1st data of 1st tuple
            self.user_data = data[0]
            self.load_user_info()
        else:
            messagebox.showerror("Error", "Incorrect email/password")

    def load_user_info(self):
        self.main_window(self.user_data)  #all the data to main window

    def logout(self):  #session expire
        self.user_id = ''
        self.user_data = ''
        self.load_gui()

    def view_others(self, index=0):  #default index=0
        #fetch data of all other users,to connect db---->dbhelper
        data = self.db.fetch_others(self.user_id)
        #print(data)
        num = len(data)
        self.main_window(data[index], mode=2, index=index,
                         num=num)  #num for number of users

    def navbar(self):  #for creating the menu bar
        menu = Menu(self.root)
        self.root.config(menu=menu)
        filemenu = Menu(menu)
        menu.add_cascade(label="Home", menu=filemenu)
        filemenu.add_command(label="My profile",
                             command=lambda: self.main_window(self.user_data)
                             )  #passing user data to main window
        filemenu.add_command(label="Edit profile",
                             command=lambda: self.edit_profile())
        filemenu.add_command(label="View profile",
                             command=lambda: self.view_others())
        filemenu.add_command(
            label="Logout",
            command=lambda: self.logout())  #for make the ac expire

        helpmenu = Menu(menu)
        menu.add_cascade(label="Proposals", menu=helpmenu)
        helpmenu.add_command(label="My proposals",
                             command=lambda: self.view_proposals())
        helpmenu.add_command(label="My requests",
                             command=lambda: self.view_requests())
        helpmenu.add_command(label="My matches",
                             command=lambda: self.view_matches())

    def view_matches(self, index=0):
        self.clear()
        # step 1:fetch data from db
        data = self.db.view_matches(self.user_id)
        # step2:call main_window func
        num = len(data)
        new_data = []
        for i in data:
            new_data.append(i[3:])
        self.main_window(new_data[index], mode=3, index=index, num=num)

    def view_requests(self, index=0):
        #step 1:fetch data from db
        data = self.db.view_requests(self.user_id)
        #step2:call main_window func
        num = len(data)
        new_data = []
        for i in data:
            new_data.append(i[3:])
        self.main_window(new_data[index], mode=3, index=index, num=num)

    def view_proposals(self, index=0):
        #step 1:fetch data from db
        data = self.db.view_proposals(self.user_id)
        #step2:call main_window func
        num = len(data)
        new_data = []
        for i in data:
            new_data.append(i[3:])
        self.main_window(new_data[index], mode=3, index=index, num=num)

    def main_window(
        self,
        data,
        mode=1,
        index=None,
        num=None
    ):  #all guis are controlled by this,mode=1-->seeing own profile
        self.clear()
        self.navbar()

        imageUrl = "images/{}".format(data[8])
        load = Image.open(imageUrl)
        load = load.resize((200, 200), Image.ANTIALIAS)
        render = ImageTk.PhotoImage(load)
        img = Label(image=render)
        img.image = render
        img.pack()

        self.label1 = Label(
            self.root, text="Name:" + data[1], fg="white",
            bg="#7D05FC")  #passing index 1=name to label in gui
        self.label1.configure(font=("Times", 15, "bold"))
        self.label1.pack(pady=(10, 10))

        if len(data[7]) != 0:
            self.label2 = Label(
                self.root, text="From:" + data[7], fg="white",
                bg="#7D05FC")  # passing index 1=name to label in gui
            self.label2.configure(font=("Times", 15, "bold"))
            self.label2.pack(pady=(10, 10))

        if len(data[6]) != 0:
            self.label3 = Label(
                self.root,
                text="Not interested in:" + data[6],
                fg="white",
                bg="#7D05FC")  # passing index 1=name to label in gui
            self.label3.configure(font=("Times", 15, "bold"))
            self.label3.pack(pady=(10, 10))

        if len(data[4]) != 0:
            self.label4 = Label(
                self.root,
                text="About me:" + data[4],
                fg="white",
                bg="#7D05FC")  # passing index 1=name to label in gui
            self.label4.configure(font=("Times", 10))
            self.label4.pack(pady=(10, 10))

        if mode == 2:  #showing others profile
            frame = Frame(self.root)
            frame.pack()

            if index != 0:
                previous = Button(
                    frame,
                    text="Previous",
                    command=lambda: self.view_others(index - 1)
                )  # adding button in frame,after 0,-1 comes,-2,---
                previous.pack(side='left')
            propose = Button(
                frame,
                text="Propose",
                command=lambda: self.propose(self.user_id, data[
                    0]))  #1st data user_id,fetching that
            propose.pack(side='left')
            if index != (num - 1):
                next = Button(frame,
                              text="Next",
                              command=lambda: self.view_others(index + 1)
                              )  #after last id,code phat rha
                next.pack(side='left')
        if mode == 3:  #showing others profile
            frame = Frame(self.root)
            frame.pack()

            if index != 0:
                previous = Button(
                    frame,
                    text="Previous",
                    command=lambda: self.view_proposals(index - 1)
                )  # adding button in frame,after 0,-1 comes,-2,---
                previous.pack(side='left')
            if index != (num - 1):
                next = Button(
                    frame,
                    text="Next",
                    command=lambda: self.view_proposals(
                        index=index + 1))  #after last id,code phat rha
                next.pack(side='left')

    def propose(self, romeo_id, juliet_id):  #from db
        response = self.db.propose(romeo_id, juliet_id)
        if response == 1:
            messagebox.showinfo("Success",
                                "Proposal sent successfully.Fingers crossed!")
        elif response == -1:
            messagebox.showerror("Error",
                                 "u have already proposed this user!!")
        else:
            messagebox.showerror("Error", "Some error occured")

    def edit_profile(self):
        self.clear()
        self.label0 = Label(self.root,
                            text="Edit Profile",
                            fg="white",
                            bg="red")
        self.label0.configure(font=("Times", 30, "bold"))
        self.label0.pack(
            pady=(10, 10))  # puts lbel on gui#three line forming label

        self.label1 = Label(self.root, text="Bio:", fg="white",
                            bg="#7D05FC")  # fg=foreground bg=background
        self.label1.configure(font=("Times", 20, "italic"))
        self.label1.pack(pady=(5, 5))  # padding in y direction

        self.bio = Entry(self.root)
        self.bio.pack(pady=(0, 10), ipadx=30, ipady=5)  # to take a text input
        # setting margin x=0,y=10,.....again setting x,y

        self.label2 = Label(self.root, text="Age:", fg="white",
                            bg="#7D05FC")  # fg=foreground bg=background
        self.label2.configure(font=("Times", 20, "italic"))
        self.label2.pack(pady=(5, 5))  # padding in y direction

        self.age = Entry(self.root)
        self.age.pack(pady=(0, 10), ipadx=30, ipady=5)

        self.label3 = Label(self.root,
                            text="Gender:",
                            fg="white",
                            bg="#7D05FC")
        self.label3.configure(font=("Times", 20, "italic"))
        self.label3.pack(pady=(5, 5))  # padding in y direction

        self.gender = Entry(self.root)
        self.gender.pack(pady=(0, 10), ipadx=30, ipady=5)

        self.label4 = Label(self.root, text="City:", fg="white", bg="#7D05FC")
        self.label4.configure(font=("Times", 20, "italic"))
        self.label4.pack(pady=(5, 5))  # padding in y direction

        self.city = Entry(self.root)
        self.city.pack(pady=(0, 10), ipadx=30, ipady=5)
        # adding button
        self.edit = Button(self.root,
                           text="Edit Profile",
                           bg="white",
                           command=lambda: self.update_profile())
        # aftter clicking button command is getting storred
        self.edit.pack(pady=(3, 10), ipadx=55,
                       ipady=0.5)  # 1 is for increasing the y height

    def update_profile(self):
        bio = self.bio.get()
        age = self.age.get()
        gender = self.gender.get()
        city = self.city.get()

        info = [bio, age, gender, city]
        response = self.db.update_profile(self.user_id, info)
        if response == 1:
            messagebox.showinfo("Successs", "Profile updated")
        else:
            messagebox.showerror("Error", "Error occupied")

    def reg_submit(self):
        name = self.name.get()
        email = self.email.get()
        password = self.password.get()
        filename = self.filename['text'].split('/')[-1]

        response = self.db.insert_user(
            name, email, password,
            filename)  #calling database function to take new input
        #print(self.filename['text'])
        #print("C:\\Users\\Chitraneswa\\PycharmProjects\\finder\\images\\th (28).jpg"+filename)
        if response == 1:
            shutil.copyfile(
                self.filename['text'],
                "C:\\Users\\Chitraneswa\\PycharmProjects\\finder\\images\\th (28).jpg"
                + filename)
            messagebox.showinfo("Registration successful",
                                "you may login now!")
        else:
            messagebox.showerror("Error", "Database Error")
Esempio n. 5
0
class quizapp:
    def __init__(self):
        self.db = DBhelper()
        self.root = Tk()

        self.root.title("My Quiz App")

        self.root.configure(background="#043CFA")

        self.root.minsize(1000, 600)
        self.root.maxsize(1000, 600)

        self.load_gui()

    def load_gui(self):
        self.clear()

        self.label1 = Label(self.root,
                            text="Quiz App",
                            fg="cyan",
                            bg="#043CFA")
        self.label1.configure(font=("Times", 30, "bold"))
        self.label1.pack(pady=(10, 20))

        self.label2 = Label(self.root, text="Email", fg="white", bg="#043CFA")
        self.label2.configure(font=("Times", 20, "italic"))
        self.label2.pack(pady=(5, 5))

        self.emailinput = Entry(self.root)
        self.emailinput.configure(font=("Times", 20, "italic"))
        self.emailinput.pack(pady=(0, 40), ipadx=40, ipady=5)

        self.label3 = Label(self.root,
                            text="Password",
                            fg="white",
                            bg="#043CFA")
        self.label3.configure(font=("Times", 20, "italic"))
        self.label3.pack(pady=(0, 5))

        self.password = Entry(self.root)
        self.password.configure(font=("Times", 20, "italic"))
        self.password.pack(pady=(0, 20), ipadx=40, ipady=5)

        self.login = Button(self.root,
                            text="Login",
                            bg="white",
                            command=lambda: self.log_in())
        self.login.configure(font=("Times", 20))
        self.login.pack(pady=(0, 50), ipadx=50, ipady=4)

        self.label4 = Label(self.root,
                            text="Not Registered?",
                            fg="white",
                            bg="#043CFA")
        self.label4.configure(font=("Times", 20, "italic"))
        self.label4.pack(pady=(10, 5))

        self.register = Button(self.root,
                               text="Sign up",
                               bg="white",
                               command=lambda: self.register_form())
        self.register.configure(font=("Times", 15))
        self.register.pack(pady=(5, 10), ipadx=30, ipady=4)

        self.root.mainloop()

    def log_in(self):
        email = self.emailinput.get()
        password = self.password.get()
        data = self.db.check_login(email, password)

        if len(data) > 0:
            self.clear()
            self.user_id = data[0][0]
            self.user_data = data[0]
            self.answer_count = 0
            self.load_user_details(mode=1)
        else:
            messagebox.showerror("Error", "Incorrect Email/password")

    def load_user_details(self, mode=None):
        if mode == 1:
            self.main_window(self.user_data, mode=1)

    def navbar(self, mode=None):

        menu = Menu(self.root)
        self.root.config(menu=menu)

        if mode == 1:
            menu.add_command(
                label="My Profile",
                command=lambda: self.main_window(self.user_data, mode=1))
            menu.add_command(label="Show Leaderboard",
                             command=lambda: self.leaders())
            menu.add_command(label="Logout", command=lambda: self.logout())
        if mode == 2:
            menu.add_command(
                label="My Profile",
                command=lambda: self.main_window(self.user_data, mode=2))
            menu.add_command(label="Show Leaderboard",
                             command=lambda: self.leaders())
            menu.add_command(label="Logout", command=lambda: self.logout())

    def leaders(self):

        topper = self.db.leader_board()
        print(topper)
        self.clear()
        self.frame6 = LabelFrame(self.root)
        self.frame6.pack(padx=30, pady=20)
        lb = Listbox(self.frame6, width=400)

        for i in range(0, len(topper)):
            lb.insert(
                i + 1, "     " + str(i + 1) + "         " + topper[i][0] +
                " (Score=" + str(topper[i][1]) + ")")
        lb.configure(font=("Times", 20, 'italic'), fg='red', bg="#22E7EA")
        lb.pack(padx=(20, 20), pady=15)

    def logout(self):
        self.navbar(mode=0)
        self.clear()
        self.load_gui()

    def main_window(self, data, mode=None):

        if mode == 1:
            self.clear()

            self.navbar(mode=1)

            imageUrl = "images/{}".format(data[6])

            load = Image.open(imageUrl)
            load = load.resize((200, 200), Image.ANTIALIAS)
            render = ImageTk.PhotoImage(load)

            img = Label(image=render)
            img.image = render
            img.pack()

            self.label1 = Label(self.root,
                                text="Name: " + " " + data[1],
                                fg="white",
                                bg="#043CFA")
            self.label1.configure(font=("Times", 20, "bold"))
            self.label1.pack(pady=(20, 30))

            self.label2 = Label(self.root,
                                text="College:  " + data[4],
                                fg="white",
                                bg="#043CFA")
            self.label2.configure(font=("Times", 15, "bold"))
            self.label2.pack(pady=(5, 30))

            self.label3 = Label(self.root,
                                text="Date of Birth:  " + str(data[5]),
                                fg="white",
                                bg="#043CFA")
            self.label3.configure(font=("Times", 15, "bold"))
            self.label3.pack(pady=(5, 40))

            self.label4 = Label(self.root,
                                text="Check your knowledge",
                                fg="#EAF4F4",
                                bg="#043CFA")
            self.label4.configure(font=("Times", 20, "bold"))
            self.label4.pack(pady=(5, 2))

            self.quiz = Button(self.root,
                               text="Quiz",
                               bg="#25F0D4",
                               command=lambda: self.quiz_window(
                                   self.user_data, mode=1, index=1))
            self.quiz.configure(font=("Times", 15, "italic"))
            self.quiz.pack(pady=(1, 5), ipadx=20)

        else:
            self.clear()
            self.navbar(mode=1)

            imageUrl = "images/{}".format(data[6])

            load = Image.open(imageUrl)
            load = load.resize((200, 200), Image.ANTIALIAS)
            render = ImageTk.PhotoImage(load)

            img = Label(image=render)
            img.image = render
            img.pack()

            self.label1 = Label(self.root,
                                text="Name: " + " " + data[1],
                                fg="white",
                                bg="#043CFA")
            self.label1.configure(font=("Times", 20, "bold"))
            self.label1.pack(pady=(20, 30))

            self.label2 = Label(self.root,
                                text="College:  " + data[4],
                                fg="white",
                                bg="#043CFA")
            self.label2.configure(font=("Times", 15, "bold"))
            self.label2.pack(pady=(5, 30))

            self.label3 = Label(self.root,
                                text="Date of Birth:  " + str(data[5]),
                                fg="white",
                                bg="#043CFA")
            self.label3.configure(font=("Times", 15, "bold"))
            self.label3.pack(pady=(5, 40))

    def quiz_window(self, data, mode=None, index=None):

        self.q_no = index

        if mode == 1:

            self.navbar(mode=0)

            self.clear()
            self.label0 = Label(self.root,
                                text="Questions",
                                fg="yellow",
                                bg="blue")
            self.label0.configure(font=("Times", 30, "bold"))
            self.label0.place(x=350, y=20)

            self.freame2 = LabelFrame(self.root, height=400, width=700)
            self.freame2.place(x=30, y=80)

            self.question = self.db.quiz_set(self.q_no)
            self.answer = self.question[0][-1]

            option = [(self.question[0][2], 1), (self.question[0][3], 2),
                      (self.question[0][4], 3), (self.question[0][5], 4)]

            self.qus = Label(self.freame2,
                             text="Q" + str(self.question[0][0]) + ". " +
                             self.question[0][1])
            self.qus.configure(font=("Times", 20, "italic"))
            self.qus.pack(padx=5, pady=10)

            self.v = IntVar()
            for text, val in option:
                self.op = Radiobutton(self.freame2,
                                      text=text,
                                      padx=20,
                                      variable=self.v,
                                      value=val,
                                      command=self.score)
                self.op.configure(font=("Times", 20))
                self.op.pack(anchor=W)

            questions = self.db.fetch_questions(self.q_no)
            self.num = len(questions)

            self.frame3 = Frame(self.root, bg='#043CFA')
            self.frame3.place(x=250, y=390)

            if index != (self.num + 1):
                self.save = Button(
                    self.frame3,
                    text="Save & Next",
                    font=("Time", 20, 'italic'),
                    bg="cyan",
                    command=lambda: self.recover(index=index + 1))
                self.save.pack()

            self.freame1 = LabelFrame(self.root, width=500, height=2000)
            self.freame1.pack(padx=(750, 10), pady=(130, 10))

            imageUrl = "images/{}".format(data[6])
            load = Image.open(imageUrl)
            load = load.resize((100, 100), Image.ANTIALIAS)
            render = ImageTk.PhotoImage(load)
            img = Label(image=render)
            img.image = render
            img.place(x=810, y=20)

            self.label1 = Label(self.freame1,
                                text="Name: " + " " + data[1],
                                fg="blue")
            self.label1.configure(font=("Times", 12, "bold"))
            self.label1.pack(pady=10)

            self.label3 = Label(self.freame1,
                                text="Your's time left",
                                fg="red",
                                bg="white")
            self.label3.configure(font=("Times", 15, "bold"))
            self.label3.pack(pady=20)

            self.label2 = Label(self.freame1, fg="red")
            self.label2.configure(font=("Times", 30, "bold"))
            self.label2.pack()
            self.countdown(remaining=600)

            self.submit = Button(self.freame1,
                                 text="Submit",
                                 bg="#25F0D4",
                                 command=lambda: self.submit_btn())
            self.submit.configure(font=("Times", 15, "italic"))
            self.submit.pack(pady=70)

        else:

            self.q_clear()

            self.question = self.db.quiz_set(self.q_no)
            self.answer = self.question[0][-1]

            option = [(self.question[0][2], 1), (self.question[0][3], 2),
                      (self.question[0][4], 3), (self.question[0][5], 4)]

            self.qus = Label(self.freame2,
                             text="Q" + str(self.question[0][0]) + ". " +
                             self.question[0][1])
            self.qus.configure(font=("Times", 20, "italic"))
            self.qus.pack(padx=5, pady=10)

            self.v = IntVar()
            for text, val in option:
                self.op = Radiobutton(self.freame2,
                                      text=text,
                                      padx=20,
                                      variable=self.v,
                                      value=val,
                                      command=self.score)
                self.op.configure(font=("Times", 20))
                self.op.pack(anchor=W)

            self.frame3 = Frame(self.root, bg='#043CFA')
            self.frame3.place(x=250, y=390)

            questions = self.db.fetch_questions(self.q_no)
            self.num = len(questions)

            if index != (self.num + 1):
                self.save = Button(
                    self.frame3,
                    text="Save & Next",
                    font=("Time", 20, 'italic'),
                    bg="cyan",
                    command=lambda: self.recover(index=index + 1))
                self.save.pack()

    def recover(self, index=None):
        self.quiz_window(self.user_data, mode=2, index=index)

    def score(self):

        if self.v.get() == self.answer:
            self.answer_count += 1

    def submit_btn(self):

        self.db.score_update(self.user_id, self.answer_count)

        self.clear()

        self.navbar(mode=2)

        self.frame5 = LabelFrame(self.root, bg='cyan').pack()
        self.awnswer_display = Label(self.frame5,
                                     text="Number of correct answer",
                                     font=("Times", 50, "italic"),
                                     fg="#FC5800",
                                     bg='black').pack(pady=(100, 5))

        self.correct = Label(self.frame5,
                             text=self.answer_count,
                             font=("Times", 80, "bold"),
                             fg='#FC5800',
                             bg='black').pack(ipadx=50, pady=30)

    def countdown(self, remaining=None):
        if remaining is not None:
            self.remaining = remaining
            self.minute = self.remaining // 60
            self.remaining = self.remaining % 60

        if self.minute == -1:
            self.label2.configure(text="Time's up!")
            self.root.after(1000, self.submit_btn)

        else:

            self.label2.configure(
                text="{}:{}".format(self.minute, self.remaining))
            self.remaining = self.remaining - 1

            if self.remaining == -1:
                self.minute -= 1
                self.remaining = 59
            self.freame1.after(1000, self.countdown)

    def register_form(self):
        self.clear()

        self.label1 = Label(self.root,
                            text="Fill the registration form carefully",
                            fg="white",
                            bg="#043CFA")
        self.label1.configure(font=("Times", 20, "italic"))
        self.label1.pack(pady=(10, 20))

        frame = Frame(self.root)
        frame.pack()

        self.label2 = Label(frame, text="Name: ", fg="white", bg="#043CFA")
        self.label2.configure(font=("Times", 20, "italic"))
        self.label2.pack(side="left")

        self.name = Entry(frame)
        self.name.configure(font=("Times", 20, "italic"))
        self.name.pack(side="left")

        frame1 = Frame(self.root)
        frame1.pack(pady=(10, 10))

        self.label3 = Label(frame1, text="Email: ", fg="white", bg="#043CFA")
        self.label3.configure(font=("Times", 20, "italic"))
        self.label3.pack(side="left")

        self.email = Entry(frame1)
        self.email.configure(font=("Times", 20, "italic"))
        self.email.pack(side="left")

        frame2 = Frame(self.root)
        frame2.pack(pady=(0, 10))

        self.label4 = Label(frame2,
                            text="Password: "******"white",
                            bg="#043CFA")
        self.label4.configure(font=("Times", 20, "italic"))
        self.label4.pack(side="left")

        self.password = Entry(frame2)
        self.password.configure(font=("Times", 20, "italic"))
        self.password.pack(side="left")

        frame3 = Frame(self.root)
        frame3.pack(pady=(0, 10))

        self.label5 = Label(frame3, text="College: ", fg="white", bg="#043CFA")
        self.label5.configure(font=("Times", 20, "italic"))
        self.label5.pack(side="left")

        self.college = Entry(frame3)
        self.college.configure(font=("Times", 20, "italic"))
        self.college.pack(side="left")

        frame4 = Frame(self.root)
        frame4.pack(pady=(0, 10))

        self.label6 = Label(frame4,
                            text='''Date of birth
        (YYYY-MM-DD): ''',
                            fg="white",
                            bg="#043CFA")
        self.label6.configure(font=("Times", 10, "italic"))
        self.label6.pack(side="left")

        self.dob = Entry(frame4)
        self.dob.configure(font=("Times", 20, "italic"))
        self.dob.pack(side="left")

        self.filebtn = Button(self.root,
                              text="Upload Pic",
                              bg="white",
                              command=lambda: self.upload_file())
        self.filebtn.pack(pady=(15, 0), ipadx=40, ipady=4)

        self.filename = Label(self.root)
        self.filename.pack(pady=(5, 5), ipadx=40, ipady=4)

        self.register = Button(self.root,
                               text="Sign Up",
                               bg="white",
                               command=lambda: self.reg_submit())
        self.register.configure(font=("Times", 15, "italic"))
        self.register.pack(pady=(20, 30), ipadx=70, ipady=4)

        self.label4 = Label(self.root,
                            text="To login Press the Button",
                            fg="white",
                            bg="#043CFA")
        self.label4.configure(font=("Times", 15, "italic"))
        self.label4.pack(pady=(10, 3))

        self.register = Button(self.root,
                               text="Sign In",
                               bg="white",
                               command=lambda: self.load_gui())
        self.register.configure(font=("Times", 10))
        self.register.pack(pady=(0, 10), ipadx=30, ipady=4)

    def upload_file(self):
        filename = filedialog.askopenfilename(initialdir="/images",
                                              title="Somrhting")
        self.filename.configure(text=filename)

    def reg_submit(self):
        name = self.name.get()
        email = self.email.get()
        password = self.password.get()
        college = self.college.get()
        dob = self.dob.get()
        filename = self.filename['text'].split('/')[-1]

        response = self.db.insert_user(name, email, password, college, dob,
                                       filename)

        if response == 1:

            shutil.copyfile(
                self.filename['text'],
                "C:\\Users\\SHIBAM\\PycharmProject\\quizapp\\images\\" +
                filename)
            messagebox.showinfo("Registration successful",
                                "You may login proceed!")
        else:
            messagebox.showerror("Database Error",
                                 " Fill the ragistration form properly")

    def clear(self):
        for i in self.root.pack_slaves():
            i.destroy()
        for i in self.root.place_slaves():
            i.destroy()

    def q_clear(self):
        for i in self.freame2.pack_slaves():
            i.destroy()
        for i in self.frame3.pack_slaves():
            i.destroy()