sujit
sujit

Reputation: 183

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

Upvotes: 5

Views: 11831

Answers (4)

PCM
PCM

Reputation: 3021

When you are importing the ttk module, you can do it in 2 ways -

  1. from tkinter import ttk When you do this, ttk is imported almost like a variable, so you can use that ttk.Label

  2. from tkinter import * This is called wildcard import. You can't use ttk.Label you have to directly write Label(options)

Upvotes: 1

Bryan Oakley
Bryan Oakley

Reputation: 386382

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.

Upvotes: 9

sujit
sujit

Reputation: 183

ttk.Label(root, text='HeadingHere').grid(row=1, column=1) 
NameError: name 'ttk' is not defined
In this remove ttk as follows.    
Label(root, text='HeadingHere').grid(row=1, column=1

Now it works fine

Upvotes: 0

falsetru
falsetru

Reputation: 369494

To import ttk, replace the following line:

from tkinter.ttk import *

with:

from tkinter import ttk

Otherwise, attributes of tkinter.ttk module will be loaded into the current module namespace instead of ttk itself.

Upvotes: 1

Related Questions