AttributeError module 'tkinter' has no attribute 'Tk'

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Mariia Forest

AttributeError module 'tkinter' has no attribute 'Tk' #

The Python "AttributeError module 'tkinter' has no attribute 'Tk'" occurs when we have a local file named tkinter.py and try to import from the tkinter module. To solve the error, make sure to rename any local files named tkinter.py.

attributeerror module tkinter has no attribute tk

Here is an example of how the error occurs in a file called tkinter.py.

tkinter.py
import tkinter as tk from tkinter import ttk # ⛔️ AttributeError: module 'tkinter' has no attribute 'Tk' root = tk.Tk() frm = ttk.Frame(root, padding=10) frm.grid() ttk.Label(frm, text="Hello World!").grid(column=0, row=0) ttk.Button(frm, text="Quit", command=root.destroy).grid(column=1, row=0) root.mainloop()

The most likely cause of the error is having a local file named tkinter.py which shadows the tkinter module from the standard library.

Make sure to rename your local file to something other than tkinter.py to solve the error.

main.py
import tkinter as tk from tkinter import ttk # ✅ Works root = tk.Tk() frm = ttk.Frame(root, padding=10) frm.grid() ttk.Label(frm, text="Hello World!").grid(column=0, row=0) ttk.Button(frm, text="Quit", command=root.destroy).grid(column=1, row=0) root.mainloop()

Make sure you haven't mistyped the import statements as that also causes the error.

You can access the __file__ property on the imported module to see whether it is shadowed by a local file.

main.py
import tkinter print(tkinter.__file__) # ⛔️ result if shadowed by local file # /home/borislav/Desktop/bobbyhadz_python/tkinter.py # ✅ result if pulling in correct module # /usr/lib/python3.10/tkinter/__init__.py

A good way to start debugging is to print(dir(your_module)) and see what attributes the imported module has.

Here is what printing the attributes of the tkinter module looks like when I have a file tkinter.py in the same directory.

main.py
import tkinter # ⛔️ ['__builtins__', '__cached__', '__doc__', '__file__', # '__loader__', '__name__', '__package__', '__spec__'] print(dir(tkinter))

If you pass a module object to the dir() function, it returns a list of names of the module's attributes.

If you try to access any attribute that is not in this list, you would get the "AttributeError: module has no attribute".

We can see that the imported tkinter module doesn't have a Tk attribute, which makes it evident that we are shadowing the official tkinter module with our local tkinter.py file.

You can use the sys module to print all of the built-in module names if you ever wonder if your local modules are clashing with built-in ones.

main.py
import sys # 👇️ print all built-in module names print(sys.builtin_module_names)
Use the search field on my Home Page to filter through my more than 1,000 articles.