TheHarpoon TheHarpoon - 3 months ago 16
Python Question

How can I integrate TKinter with Python log in screen?

I am using TkInter to create a log in screen here, at the moment the keep me logged in button at the bottom is redundant and will remain so. What I want to do is use this code:

from tkinter import *

root = Tk()

label_1 = Label(root, text="Username")
label_2 = Label(root, text="Password")

entry_1 = Entry(root)
entry_2 = Entry(root)

label_1.grid(row=0, sticky=E)
label_2.grid(row=1, sticky=E)
entry_1.grid(row=0, column=1)
entry_2.grid(row=1, column=1)

checkbox = Checkbutton(root, text="Keep me logged in")
checkbox.grid(columnspan=2)


in conjunction with:

username = "john"
input("Username: ")
while not username:
if username == "john":
print("Welcome")
else:
print("User not found")


password = "password"
while not password:
input("password: ")
if password == "password":
print("Logged in")
else:
print("Incorrect password")


However the logging in code does not work and then on top of that I do not know where to begin with integrating the two with each other.
I am some what new to python and even more so to TkInter but am desperate for this help!

Thanks in advance!

Answer

I extended your example. I made a class that holds your login window.

from tkinter import *
import tkinter.messagebox as tm


class LoginFrame(Frame):
    def __init__(self, master):
        super().__init__(master)

        self.label_1 = Label(self, text="Username")
        self.label_2 = Label(self, text="Password")

        self.entry_1 = Entry(self)
        self.entry_2 = Entry(self, show="*")

        self.label_1.grid(row=0, sticky=E)
        self.label_2.grid(row=1, sticky=E)
        self.entry_1.grid(row=0, column=1)
        self.entry_2.grid(row=1, column=1)

        self.checkbox = Checkbutton(self, text="Keep me logged in")
        self.checkbox.grid(columnspan=2)

        self.logbtn = Button(self, text="Login", command = self._login_btn_clickked)
        self.logbtn.grid(columnspan=2)

        self.pack()

    def _login_btn_clickked(self):
        #print("Clicked")
        username = self.entry_1.get()
        password = self.entry_2.get()

        #print(username, password)

        if username == "john" and password == "password":
            tm.showinfo("Login info", "Welcome John")
        else:
            tm.showerror("Login error", "Incorrect username")




root = Tk()
lf = LoginFrame(root)
root.mainloop()

Sorry for not going over every single line what is happening there. I leave it to you to figure out. Its good exercise. But I will say that the most important is command = self._login_btn_clickked. This function will be executed when you click login button. In this function, you take the values of username and password, and check if they are correct. Also I did not attach any callbacks to the checkbox. But it would be similar to what is already done.

enter image description here

Comments