Search code examples
pythonpython-3.xtkinterttk

why does tkinter ttk showing "name ttk is not defined" in python 3.5.1


Consider this simple code:

from tkinter import *
from tkinter.ttk import *
root= Tk()
ttk.Label(root, text='Heading Here').grid(row=1, column=1)
ttk.Separator(root,orient=HORIZONTAL).grid(row=2, columnspan=5)
root.mainloop()

when i run this code it's showing error

ttk.Label(root, text='Heading Here').grid(row=1, column=1)
NameError: name 'ttk' is not defined

Solution

  • When you do import X, you are importing a module named X. From this point on, X will be defined.

    When you do from X import *, you are not importing X, you are only importing the things that are inside of X. X itself will be undefined.

    Thus, when you do from tkinter.ttk import *, you are not importing ttk, you are only importing the things in ttk. This will import things such as Label, Button, etc, but not ttk itself.

    The proper way to import ttk in python3 is with the following statement:

    from tkinter import ttk  
    

    With that, you can reference the ttk label with ttk.Label, the ttk button as ttk.Button, etc.

    Note: doing from tkinter.ttk import * is dangerous. Unfortunately, ttk and tkinter both export classes with the same name. If you do both from tkinter import * and from tkinter.ttk import *, you will be overriding one class with another. The order of the imports will change how your code behaves.

    For this reason -- particularly in the case of tkinter and ttk which each have several classes that overlap -- wildcard imports should be avoided. PEP8, the official python style guide, officially discourages wildcard imports:

    Wildcard imports ( from import * ) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools.


    Note: your question implies you're using python 3, but in case you're using python 2 you can just do import ttk rather than from tkinter import ttk. ttk moved in python 3.