Search code examples
pythontkintersticky

How to set the button sticky property properly?


I've been playing around with tkinter a bit and I can't figure out why the "sticky" attribute doesn't seem to be working with my button. I've specified sticky to be NW which should cause my button to stick to the top left edge but for some reason it sticks to the top right. Any idea why?

from tkinter import *
from tkinter import ttk

def test():
    name = userName.get()
    text = "Hello {0}! Pleased to meet you.".format(name)
    greeting.set(text)

window = Tk()

greeting = StringVar()
userName = StringVar()

name = Entry(window, textvariable=userName)
name.grid(column=1, row=1, sticky=NW)

button = Button(window, text="greeting", command=test)
button.grid(column=2, row=1, sticky=NW)

label = Label(window, textvariable=greeting)
label.grid(column=1, row=2, sticky=NW)

#creating a rectangle
canvas = Canvas(window)
canvas.grid(column=1, row=2)
#attributes are x,y coordinates of two points
x = canvas.create_rectangle(5,5,115,115)    

mainloop()

Solution

  • The sticky attribute applies to the cell that the widget is in, rather than to the whole grid or whole window. So, the widget is anchored to the nw corner of its cell, it's just that you can't tell because the cell is exactly the same width as the button.

    Since you are placing the button in the upper right cell (row 1, column 2) but say you want it in the upper left (of the whole window?) it's hard to know exactly what you want. Without knowing what you're trying to achieve it's hard to make any recommendations.

    The easiest way to learn the grid layout manager is with paper and pencil. Get out some gridded graphing paper and draw your widgets on the paper. It then becomes obvious where to put your widgets.

    You also need to learn about the rowconfigure and columnconfigure commands, especially with respect to the weight attribute. With this attribute you can identify which rows and columns grown and shrink to take up any extra space. It's also useful to know you can apply these attributes to empty rows and columns. This is useful if you want your interior widgets to stay the same size, and have any extra applied to the edges of your gui (generally not useful, though sometimes it is).

    As a rough rule of thumb, each window should have one "major" widget -- the one that dominates the UI. Usually this is a canvas or text widget, but it doesn't have to be. Find that widget and give the row and column it is in a weight of 1 (one) so that it grows and shrinks as the user resizes the window. In your case this would be the canvas in row 2, column 1.