Search code examples
pythontkintersticky

what is the difference between tkinter sticky formats


I'm trying to learn tkinter but I haven't been able to find an answer that explains why I see examples of the 'sticky' option written in different formats, for example:

enter sticky = N+E+S+W
sticky=NW
sticky="ew"
sticky=tk.W+tk.N

Is there any significance to the capitalization (I think normally signifies a constant), the + signs (string concatination), and the tk. (a method). Is it personal preference, do they do different things, or does it depend on the context they are being used in?


Solution

  • N, S, E, and W are constants defined by the tkinter module. These each contain a string with a single character matching the name (eg: N = "n"). Because they are global constants, they are uppercase to be compliant with PEP8.

    The reason you sometimes see the constants prefixed with tk. or tkinter has to do with how the constants are imported. If you do from tkinter import * you don't use the prefix. If you use import tkinter you use the tkinter. prefix. if you use import tkinter as tk you use the tk. prefix. This isn't anything unique to tkinter, it's how importing works in all of python.

    The sticky attribute requires a string. That is the only thing it accepts. The string can contain any of the characters "n", "s", "e", "w". Tkinter doesn't care how you create the string. You can pass "nsew", "news", N + "e" + "s" + W or any other technique.

    Personally, I find the constants useless. It's much easier just to use the literal string.