1

After doing from tkinter import * why is ttk not defined? What does * mean?

>>> from tkinter import *
>>> root = Tk()
>>> asd = ttk.Treeview(root)
Traceback (most recent call last):
  File <"pyshell#4">, line 1, in <module>
    asd = ttk.Treeview(root)
NameError: name 'ttk' is not defined

If I do from tkinter import ttk, then there is no problem. On using *, ttk must have been fetched. Then why is there an error?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
ashish7249
  • 269
  • 3
  • 7
  • 1
    *"On using `*`, `ttk` must have been fetched."* - no, that's not correct. `ttk` isn't exposed in the module's [`__init__.py`](https://hg.python.org/cpython/file/3.5/Lib/tkinter/__init__.py). If you don't know what `*` means in this context, see http://stackoverflow.com/q/2360724/3001761. – jonrsharpe Nov 02 '16 at 21:00

2 Answers2

1

What follows below is just elaborating on jonrsharpe's great comment that I think answers the question.

Python's from package import * indeed looks deceptively like it imports everything from said package, but this is not the case. The docs say:

The import statement uses the following convention: if a package’s __init__.py code defines a list named __all__, it is taken to be the list of module names that should be imported when from package import * is encountered.

So if there is an __init__.py file in the package directory (it has to, otherwise it's not gonna be imported anyway) and it contains a list named __all__ than this list's contents are treated as module names to be imported into the calling module's namespace.

What happens if __all__ variable is not defined in __init__.py? Paraphrasing a further paragraph from the docs:

If __all__ is not defined, the statement from package import * does not import all submodules from the package into the current namespace; it only ensures that the package has been imported (possibly running any initialization code in __init__.py) and then imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by __init__.py. It also includes any submodules of the package that were explicitly loaded by previous import statements.

If you want a good example where understanding this is crucial, head over to video #20 introducing GUI programming with TkInter in Derek Banas's excellent Python YT series.

z33k
  • 3,280
  • 6
  • 24
  • 38
0

The official python documentation reveals the answer

You can either do

from tkinter import ttk

Or

from tkinter import *
from tkinter.ttk import *

The second method overrides the 'original' tkinter widgets with the ttk versions. So just doing from tkinter import * means that you want to use the 'original' widgets.

scotty3785
  • 6,763
  • 1
  • 25
  • 35