pythontkintertkinter-entrytkinter-label

How to Adjust Spacing Between Label and Entry Widget in Tkinter Password Generator Layout?


I have a Tkinter-based Password Generator with a layout that includes a "Password Length" label and an entry widget. However, I would like to adjust those elements to the center of that row. The current layout works perfectly, but this adjustment would enhance the visual appeal of the application. I have included the complete working code below and the output for reference:

import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import random
import string
import pyperclip

def generate_password(length):
    characters = string.ascii_letters + string.digits + string.punctuation
    password = ''.join(random.choice(characters) for _ in range(length))
    return password

def generate_and_display_password():
    try:
        length = int(length_entry.get())

        if 8 <= length <= 50:
            password = generate_password(length)
            password_var.set(password)
        else:
            messagebox.showerror("Error", "Invalid password length. Please enter a value between 8 and 50.")
    except ValueError:
        messagebox.showerror("Error", "Invalid input. Please enter a valid integer.")

def clear_password():
    password_var.set("")

def copy_to_clipboard():
    password = password_var.get()
    pyperclip.copy(password)
    messagebox.showinfo("Copied", "Password copied to clipboard!")
    clear_password()

# Create main window
window = tk.Tk()
window.title("Password Generator")

# Set minimum window size
window.minsize(310, 120)

# Disable window resizing
window.resizable(False, False)

# Create and pack widgets
length_label = ttk.Label(window, text="Password Length:")
length_label.grid(row=0, column=0, padx=10, pady=5, sticky="e")

length_entry = ttk.Entry(window, width=5)
length_entry.grid(row=0, column=1, padx=10, pady=5)

generate_button = ttk.Button(window, text="Generate Password", command=generate_and_display_password)
generate_button.grid(row=1, column=0, columnspan=2, pady=10)

password_var = tk.StringVar()
password_label = ttk.Label(window, text="Generated Password:")
password_label.grid(row=2, column=0, padx=10, pady=10, sticky="e")

password_entry = ttk.Entry(window, textvariable=password_var, state="readonly", width=30)
password_entry.grid(row=2, column=1, padx=10, pady=10, sticky="w")

copy_button = ttk.Button(window, text="Copy to Clipboard", command=copy_to_clipboard)
copy_button.grid(row=3, column=0, pady=10, columnspan=2)

clear_button = ttk.Button(window, text="Clear Password", command=clear_password)
clear_button.grid(row=4, column=0, pady=10, columnspan=2)

# Center the window content
window.update_idletasks()
width = window.winfo_width()
height = window.winfo_height()
x = (window.winfo_screenwidth() // 2) - (width // 2)
y = (window.winfo_screenheight() // 2) - (height // 2)
window.geometry('{}x{}+{}+{}'.format(width, height, x, y))

# Start the Tkinter event loop
window.mainloop()

Output of the above code:

output of the above code

I tried to do some changes in line 46 and 49 but those two elements goes all over the place. It doesn't fix the the issue whatsoever. I appreciate any assistance in making this adjustment. Thank you!


Solution

  • If I understand what you're asking correctly, you can just add sticky='w' to the length_entry.grid() call to get it to "stick" to the left-hand side of the column

    length_entry.grid(row=0, column=1, padx=10, pady=5, sticky='w')
    

    Note that if you want to the length entry to span the entire 2nd column (similar to password_entry) you can use sticky='ew' instead

    This isn't techically centering the length_entry widget, but it does align it with the left side of password_entry which does look a bit neater (IMO)

    I should also point out for anyone curious that the reason password_entry fills the entire 2nd column is because it's width is set to 30 which is (apparently) wider than the 2nd column and fills the whole thing.