简体   繁体   中英

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?

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 Button s and Frame s 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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM