21

I'm trying to test GUI code using Python 3.2 with standard library Tkinter but I can't import the library.

This is my test code:

from Tkinter import *

root = Tk()
w = Label(root, text="Hello, world!")
w.pack()
root.mainloop()

The shell reports this error:

Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
from Tkinter import *
ImportError: No module named Tkinter
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
carryall
  • 482
  • 3
  • 10
  • 21
  • This was wrongly closed. The original duplicate was about Tkinter being missing on some installations of Python. This one is about the change in the module's name (from uppercase to lowercase t) from Python 2 to Python 3. However, I found a more comprehensive duplicate that is actually specific to the question, and also has a better title for future viewers. – Karl Knechtel Apr 25 '23 at 17:55

3 Answers3

37

The root of the problem is that the Tkinter module is named Tkinter (capital "T") in python 2.x, and tkinter (lowercase "t") in python 3.x.

To make your code work in both Python 2 and 3 you can do something like this:

try:
    # for Python2
    from Tkinter import *
except ImportError:
    # for Python3
    from tkinter import *

However, PEP8 has this to say about wildcard imports:

Wildcard imports ( from <module> import * ) should be avoided

In spite of countless tutorials that ignore PEP8, the PEP8-compliant way to import would be something like this:

import tkinter as tk

When importing in this way, you need to prefix all tkinter commands with tk. (eg: root = tk.Tk(), etc). This will make your code easier to understand at the expense of a tiny bit more typing. Given that both tkinter and ttk are often used together and import classes with the same name, this is a Good Thing. As the Zen of python states: "explicit is better than implicit".

Note: The as tk part is optional, but lets you do a little less typing: tk.Button(...) vs tkinter.Button(...)

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
Ben Gates
  • 762
  • 5
  • 14
20

The module is called tkinter, not Tkinter, in 3.x.

Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224
10

Rewrite the code as follows with Tkinter as tkinter (lowercase) for 3.x:

from tkinter import *

root = Tk()

w = Label(root, text="Hello, world!")
w.pack()

root.mainloop()
Musaab
  • 1,574
  • 3
  • 18
  • 37