5
votes

All tutorials simply import tkinter,

I am wondering, though, why not import _tkinter? If my understanding is correct, _tkinter is the actual library in cpython and tkinter is the interface or API.

I am simply trying to grasp the paradigm as I read through some of the tkinter source code. It seems there is some python black magic afoot.

3
I think your understanding is correct. - Nae
Just open the tkinter/__init__.py file to see all of the code that tkinter provides. You'd have to do all that manually if you used import _tkinter. Use import tkinter; print(tkinter.__file__) to find the file. - Novel

3 Answers

9
votes

_tkinter is a C-based module that wraps an internal tcl/tk interpreter. When you import it, and it only, you get access to this interpreter but you do not get access to any of the python classes.

You certainly can import _tkinter, but then you would have to recreate all of the python interfaces to the tcl/tk functions.

2
votes

In python "_" marks a variable is intended for internal use

This convention is defined in PEP 8, but isn't enforced by Python

You shouldn't import class/modules/variables starting with "_" due to that nature, the developer should allow a property/setter methods to access those attributes..

For python2 use "Tkinter"

For python3 use "tkinter"

http://pep8.org/#descriptive-naming-styles

0
votes

According to the documentation,

The Tk interface is located in a binary module named _tkinter. This module contains the low-level interface to Tk, and should never be used directly by application programmers.

So the somewhat unsatisfying answer to "why not import _tkinter?" is "because the language developers told us not to".