grid layout just not aligning perfectly, even when following lecturer's code

Question:

I’m learning python doing a udemy course so its watching pre-recorded videos.
Following on recording laying out widgets on a screen (using tKinter) and just cannot get one button to align – even though I literally copy the code the lecturer has in the recording.
I am sure I am missing something really simple here. Everything lines up except the "Generate Password" button which is off to the right.
Its just a basic intro right now to GUI in Tkinter – so haven’t gone into Frames as yet – just basic layouts.

Code is here – Everything aligns beautifully except the "Generate Password" button which shows up too far to the right – almost as if it is in another column…

from tkinter import *

def generate_pwd():
    pass

def add_pwd():
    pass
window = Tk()
window.title("Password Manager")
window.config(padx=50, pady=50)

# background canvas
canvas = Canvas(width=200, height=200)
img_lock = PhotoImage(file="logo.png")
canvas.create_image(100, 100, image=img_lock)
canvas.grid(column=1, row=0)

# widgets
lbl_website = Label(text="Website:")
lbl_website.grid(column=0, row=1, sticky=W)

lbl_email = Label(text="Email/UserName:")
lbl_email.grid(column=0, row=2, sticky=W)

lbl_password = Label(text="Password:")
lbl_password.grid(column=0, row=3, sticky=W)

ent_website = Entry(width=42)
ent_website.grid(column=1, row=1, columnspan=2, sticky=W)

ent_email = Entry(width=42)
ent_email.grid(column=1, row=2, columnspan=2, sticky=W)

ent_password = Entry(width=21)
ent_password.grid(column=1, row=3, sticky=W)

btn_generate = Button(text="Generate Password", command=generate_pwd)
btn_generate.grid(column=2, row=3)

btn_add = Button(text="ADD", width=35, command=add_pwd)
btn_add.grid(column=1, row=4, columnspan=2, sticky=W)


window.mainloop()

What I get:

What_I_Get

Asked By: jureidinim

||

Answers:

From what I read, the width of a column is by default the width of its widest element; in your case, the culprit is the logo with its width of 100 that makes column 1 wider than it should be.

To fix this, just add a columnspan of 2 in your logo placement (in addition, the logo will be nicely centered):

...
canvas.create_image(100, 100, image=img_lock)
canvas.grid(column=1, row=0, columnspan=2)
...
Answered By: Swifty
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.