Anthonyrr2
Anthonyrr2

Reputation: 43

How does the sticky command affect the python code in Tkinter?

from tkinter import *
from tkinter import ttk

root = Tk()

root.rowconfigure(0,weight = 1)
root.columnconfigure(0,weight = 1)

frame = ttk.Frame(root)
frame.grid(row = 0,column =0)

ttk.Label(frame,text = 'Label_1').grid(row=0,column=0,sticky='nsew')
ttk.Button(frame,text = 'Button').grid(row=0,column=1,sticky='nwse')
ttk.Label(frame,text = 'Label_2').grid(row=0,column=2,sticky='nwes')

root.mainloop()

I don't see the difference in the output clearly if either I remove the sticky or leave it. So how does the sticky affect my code?

Upvotes: 3

Views: 10005

Answers (2)

Bryan Oakley
Bryan Oakley

Reputation: 386285

The sticky option tells tkinter what to do if there's more room for the widget than needed. It tells tkinter which sides of the empty space the widget needs to "stick" to.

In your case, the window fits the widget exactly so you'll see no difference.

Upvotes: 3

kabanus
kabanus

Reputation: 25980

To see the difference you need to give tkinter a reason to not fit the cell exactly around your widget, which it will always do by default if possible. Try:

from tkinter import *
from tkinter import ttk

root = Tk()

root.rowconfigure(0,weight = 1)
root.columnconfigure(0,weight = 1)

frame = ttk.Frame(root)
frame.grid(row = 0,column =0)

ttk.Label(frame,text = 'Label_1',background='red').grid(row=0,column=0,sticky='nwes')
ttk.Button(frame,text = 'Button').grid(row=0,column=1,sticky='nwse')
ttk.Label(frame,text = 'Label``_2').grid(row=0,column=2,sticky='nwes')
ttk.Label(frame,text = 'LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG').grid(row=1,column=0)
root.mainloop()

and next remove ,sticky='news' from Label_1. Note that the text centering and widget centering are two different things - that's why I gave a background color, to make it evident.

Also, you do not really need ttk, you get your Buttons and Frames from from tkinter import * already, though I would explicitly list them as in from tkinter import Button,Frame,Tk or use import tkinter as tk and use tk.Label.

Upvotes: 4

Related Questions