5

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.

IAbstract
  • 19,551
  • 15
  • 98
  • 146
  • I think your understanding is correct. – Nae Jan 22 '18 at 15:36
  • 1
    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 Jan 22 '18 at 20:18

3 Answers3

9

_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.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
2

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

Ragnarok
  • 170
  • 14
0

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".

Kevin
  • 74,910
  • 12
  • 133
  • 166
  • 3
    Unsatisfying is an understatement. What do we do as soon as someone says, "Don't do --fill in the blank--"? – IAbstract Jan 22 '18 at 23:44