Last updated: Apr 8, 2024
Reading time·2 min
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
.
Here is an example of how the error occurs in a file called 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()
If you get the error "ModuleNotFoundError: No module named 'tkinter'", click on the following article.
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.
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()
You can name your file main.py
or use any other name that doesn't clash with a
module.
If you have issues importing tkinter
or using the module, check out my
ModuleNotFoundError: No module named 'tkinter'
article.
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.
import tkinter print(tkinter.__file__) # ⛔️ The result is shadowed by a local file # /home/borislav/Desktop/bobbyhadz_python/tkinter.py # ✅ The result is pulling in the 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.
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.
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.
import sys # 👇️ Print all built-in module names print(sys.builtin_module_names)