Python Tkinter: Why use Tkinter.W not str "w" Python Tkinter: Why use Tkinter.W not str "w" tkinter tkinter

Python Tkinter: Why use Tkinter.W not str "w"


I always use the string value. I see absolutely no benefit in using the constants. The chance of them changing is virtually zero. These constants have remained unchanged since Tkinter was created.

tkinter takes backwards compatibility pretty seriously, so even if they are changed, the string values will undoubtedly continue to work for a year or two.

My recommendation is to never use the constants.


This is done mostly for user convinience.

Consider the Image class from PIL/Pillow. It has a method to create a thumbnail out of an image, in the process resizing it. The method takes two arguments, the new size in a tuple and a resampling method. This can be antialias, bilinear, cubic, etc. These are internally represented with integer values, like 0, 1, etc. If you don't know which value represents which resampling method, it's cumbersome to look it and may also lead to more errors. But access it from the constant Image.BILINEAR and boom, you're done.

In your case, importing W just for the string "w" seems to be needlessly polluting the namespace and typing tkinter.W is longer than "w". This might be so. However, remember, constants in a program are defined in one place so if you ever have to change them, it will be easy to so. You never know, the module may be internally use the constant W, even if you see no point in it.

This also leads to the reason you pointed out. A constant may have a different value depending on the system or version. By using the internally consistent constant and not a static, hardcoded value, you make your life easier when you reuse that code on a diferent system or version.