Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 829
Anthonyrr2 Avatar asked Sep 02 '26 23:09

Anthonyrr2


2 Answers

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.

like image 108
kabanus Avatar answered Sep 05 '26 14:09

kabanus


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.

like image 42
Bryan Oakley Avatar answered Sep 05 '26 15:09

Bryan Oakley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!