Home > Blockchain >  Tkinter login page layout problem - Python
Tkinter login page layout problem - Python

Time:12-17

I'm trying to create a login page in Tkinter with .pack(). I wold like to place the loginFrame at the center of the small window. And inside the loginFrame, the username section on top of the password section.

def main():
    window = tk.Tk()
    window.geometry("400x200")
    window.title("PySploit")
    window.resizable(False, False)
    window.configure(background="#E1E5F2")

    loginFrame = tk.Frame(window).pack(anchor="center")

    usernameFrame = tk.Frame(loginFrame).pack(side=LEFT)
    passwordFrame = tk.Frame(loginFrame).pack(side=LEFT)

    tk.Label(usernameFrame, text="Username").pack(side=LEFT)
    tk.Entry(usernameFrame, name="username").pack(side=LEFT)

    tk.Label(passwordFrame, text="Password").pack(side=LEFT)
    tk.Entry(passwordFrame, name="password").pack(side=LEFT)
    
    window.mainloop()
    return

if __name__ == "__main__":
    main()

This is my wrong output:

This is my output

CodePudding user response:

For your requirement, you don't need usernameFrame and passwordFrame, just loginFrame is enough.

You can put loginFrame at the center of the window using place() instead and put those labels and buttons inside loginFrame using grid():

import tkinter as tk

def main():
    window = tk.Tk()
    window.geometry("400x200")
    window.title("PySploit")
    window.resizable(False, False)
    window.configure(background="#E1E5F2")

    loginFrame = tk.Frame(window)
    # place loginFrame at the center of window
    loginFrame.place(relx=0.5, rely=0.5, anchor='c')

    # use grid() instead of pack() to lay out labels and entries
    tk.Label(loginFrame, text="Username").grid(row=0, column=0)
    tk.Entry(loginFrame, name="username").grid(row=0, column=1)

    tk.Label(loginFrame, text="Password").grid(row=1, column=0)
    tk.Entry(loginFrame, name="password").grid(row=1, column=1)

    window.mainloop()


if __name__ == "__main__":
    main()
  • Related