Why does tkinter (or turtle) seem to be missing or broken? Shouldn't it be part of the standard library?
Asked Answered
G

4

20

I have seen many different things go wrong when trying to use the Tkinter standard library package, or its related functionality (turtle graphics using turtle and the built-in IDLE IDE), or with third-party libraries that have this as a dependency (e.g. displaying graphical windows with Matplotlib).

It seems that even when there isn't a problem caused by shadowing the name of the standard library modules (this is a common problem for beginners trying to follow a tutorial and use turtle graphics - example 1; example 2; example 3; example 4), it commonly happens that the standard library Tkinter just doesn't work. This is a big problem because, again, a lot of beginners try to follow tutorials that use turtle graphics and blindly assume that the turtle standard library will be present.

The error might be reported:

Why do problems like this occur, when Tkinter is documented as being part of the standard library? How can I add or repair the missing standard library functionality? Are there any special concerns for specific Python environments?


See also: "UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm . It is possible to use other GUI backends with Matplotlib to display graphs; but if the TkAgg backend does not work, that is because of a missing or faulty Tkinter install.

In Python 3.x, the name of the Tkinter standard library module was corrected from Tkinter to tkinter (i.e., all lowercase) in order to maintain consistent naming conventions. Please use Difference between tkinter and Tkinter to close duplicate questions caused by trying to use the old name in 3.x (or the new name in 2.x). This question is about cases where Tkinter is not actually available. If it isn't clear which case applies, please either offer both duplicate links, or close the question as "needs debugging details".

Gudrin answered 25/4, 2023 at 20:32 Comment(12)
This is an attempt at an artificial canonical duplicate. I already have several questions earmarked to dupe-hammer to here; a few of the popular questions I linked here should remain open, but I'm hoping this question will be a better dupe target for most new questions.Gudrin
Help wanted: looking for information about various "special" environments like QGIS, debug builds (as described in e.g. stackoverflow.com/questions/62743762) etc.Gudrin
One very specific hiccup with PyPy: stackoverflow.com/questions/59764766 And with PyInstaller: stackoverflow.com/questions/39135408Gudrin
Also: stackoverflow.com/questions/46613117Gudrin
Why are you closing older questions as duplicates of this newer question? If this question is newer, isn't it by definition a duplicate of the older questions?Abbey
Closing a question that is over 8 years old, has a score of nearly 400 and has been viewed 900,000 times as a duplicate of an "artificial canonical" seems a bit excessive.Novelette
@CarlG, age is not a factor when considering which question is the duplicate. The quality of each question, and their answers, should be used to determine which is the "dupe" and which is canonical. See meta.https://mcmap.net/q/46305/-how-do-you-use-source-control-without-ide-integration-closedSlemmer
Thanks, Chris. I would say this case from that meta answer applies: "If they differ based on the versions of the relevant systems, then they're not really exact duplicates." My question is specific to pyenv (which makes it easier for pyenv users to find and faster to fix their issue) while this artificial canonical tries to address the problem theoretically, and links back to mine for pyenv specifically.Abbey
stackoverflow.com/questions/36760839 was marked as a duplicate when it's really targeting OSX users, this question and it's answers don't address what people searching for that problem. That said, https://mcmap.net/q/146338/-why-does-tkinter-or-turtle-seem-to-be-missing-or-broken-shouldn-39-t-it-be-part-of-the-standard-library provides a solution but not as targeted as the question's answers I referenced.Hatpin
@IuriGuilherme In the main answer, I back-link that Q&A while giving what I believe to be a fair summary of the Mac-specific aspects of the issue. I wrote this one because a general understanding is necessary for the issue (in particular, the advice to avoid Pip applies regardless of platform) and because platform-specific aspects are really just finer detail. The common threads here are that there are platform-agnostic reasons Tkinter might be missing; you need to do system package-management or build-from-source type things to get it; and there are dependencies external to Python itself.Gudrin
@KarlKnechtel I agree and disagree with you at the same time. My answer on the referenced question gives enough depth without addressing every aspect of the problem, which may be of no interest to people who just want to make it work on a Macbook for example. And even with all your research, the subject can be further explained, so where to draw the line remains to the scope of the question. This is not wikipedia IMOHatpin
Sorry, but this reads like a blog-post or a tutorial, and not a question/answer (which is the focus of Stack Overflow)...Lytle
G
35

WARNING: Do not use pip to try to solve the problem

The Pip package manager cannot help to solve the problem. No part of the Python standard library - including tkinter, turtle etc. - can be installed from PyPI. For security reasons, PyPI now blocks packages using names that match the standard library.

There are many packages on PyPI that may look suitable, but are not. Most are simply wrappers that try to add a little functionality to the standard library Tkinter. However, one especially problematic package is turtle. It should not be there, because current policy (since 2017) is to block packages with names that match the standard library; but it was uploaded long before that, and has not been maintained since. It is Python 2.x specific code that will break during installation on Python 3, is extremely out of date (published in 2009) and - most importantly - has nothing whatsoever to do with turtle graphics. I am currently attempting to get it delisted from PyPI.

Why some Python installations don't include Tkinter components

There are several reasons why Tkinter might be missing, depending on the platform (although generally, the motivation is probably just to save space).

  • When Python is installed on Windows using the official installer, there is an option to include or exclude Tcl/Tk support.

  • Python installations that come pre-installed with Linux may exclude Tkinter, or various components, according to the distro maintainer's policy. For example, the Python that came with my copy of Linux included the turtle standard library, but not the underlying Tkinter package:

    >>> import turtle
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/lib/python3.8/turtle.py", line 107, in <module>
        import tkinter as TK
    ModuleNotFoundError: No module named 'tkinter'
    

    Other builds might not include the turtle module either.

  • Python built from source might be missing Tkinter support because of deliberately chosen configuration options, or because dependencies were missing before starting compilation.

Note that virtual environments will generally have the same Tkinter support as the Python installation they're based upon. However, adding Tkinter support to the base might not update the virtual environment. In this case, it will be necessary to re-create the virtual environment from scratch. It is not possible to add or remove Tkinter support for an individual virtual environment. This is because a virtual environment only differs from its base in terms of the site packages, and there is no site package for Tkinter (since, again, it is a standard library component that cannot be obtained using Pip).

How to add Tkinter support, depending on the environment

See also:

Windows

For Python installed using the official installer from python.org, use the operating system features to choose to "repair" the installation (or, if acceptable, uninstall and reinstall Python). This time, make sure to check the option to install the "tcl/tk and IDLE" optional feature.

Some legacy setups may have had issues with conflicts between 32- and 64-bit versions of Python and Tcl/Tk. This should not cause problems on new setups.

For the embeddable zip package, see Python embeddable zip: install Tkinter .

Linux: Python that came with the Linux distribution

If the Python that came with your Linux distribution doesn't include Tkinter, consider leaving that alone and installing a separate version of Python - just on general principle. However, in general, Tkinter support can be added to the system Python using the system package manager (not Pip).

It will typically be necessary to use sudo (not included in examples here) to make such changes to the system Python.

  • On Ubuntu and Debian based systems (including Pop!_OS, Ubuntu-based Mint): use apt-get install python3-tk, assuming the system Python is a 3.x version. For 2.x legacy systems, use apt-get install python-tk instead. In some cases it may be necessary to specify a minor version, like apt-get install python3.11-tk. In some cases, a custom exception message may say to install python-tk even though python3-tk should actually be installed instead.

  • For Fedora, use dnf install python3-tkinter, as described by d-coder here.

  • For Arch, use pacman -S tk, as described by Jabba here.

  • For RHEL, use yum install python3-tkinter, as described by amzy-0 here.

Linux: Python built from source

The above packages can only add Tkinter support to the system python (the one installed in /usr/bin, which is used by the operating system to run essential scripts). They cannot add Tkinter support to a separate Python built from source. This is because, in addition to the actual Tcl/Tk library, using Tkinter in Python requires a per-installation "binding" library (referred to as _tkinter in the Python source code). System packages will not add this library to other Python installations.

Therefore, install a development Tk package first (e.g. apt-get install tk-dev) and try rebuilding.

See also:

Brew (typically MacOS)

Use brew install python-tk; if necessary, specify a Python version like brew install [email protected].

For non-system installations, it may be necessary to re-install and specify that Tkinter support should be included, like brew install python --with-tcl-tk. See also: Why does Python installed via Homebrew not include Tkinter

Headless environments

It's generally not possible to install Tkinter - or any other GUI toolkit - for headless server environments like PythonAnywhere or Amazon Linux EC2. The code will run on a remote server, so there is no monitor to display the GUI; while it would be possible in principle for the code to send commands back to the client that the client could then use to create a GUI, in general the server will have no knowledge of the client's environment. Making this work would require setting up some communication protocol ahead of time (such as X11).

Virtual environments

First, fix the installation that the virtual environment is based upon. If this doesn't resolve the problem, re-create the virtual environment (and reinstall everything that was installed in the old virtual environment). Unfortunately, there is not a clean way around this. It might be possible to patch around the problem by changing a bunch of symlinks, but this is not supported.

If it is not possible to fix the base installation (for example, due to not having sudo rights on the system), consider installing a separate Python (for example, by compiling from source), ensuring that it is installed with Tkinter support, and creating virtual environments from that Python.

Additional hints: TKinter in a Virtualenv

Tkinter components

Some users will find it useful to understand exactly what the Tkinter system contains. There are several components:

  • The underlying Tcl/Tk library, written in C. Some systems may independently have a Tcl/Tk installation that is unusable from Python by default.

  • The _tkinter implementation module, which is also written in C and which interfaces between Python and Tcl/Tk ("tkinter" means "Tk interface"). This is an implementation detail, and should not be imported directly in Python user code. (the C code for this dates all the way back to 1994!)

  • The tkinter package itself, which provides wrappers for the lower-level _tkinter interface, as well as ttk (a separate interface for newer "themed" widgets).

  • Higher-level components, such as IDLE and turtle.

Any given installation could theoretically be missing any or all of these components. For system installations of Python on Linux and MacOS, the distro maintainer is responsible for making sure that the appropriate package (python3-tk or similar) installs whichever parts are missing by default, to the appropriate places.

As explained to me on GitHub by Terry Jan Reedy: when the Windows installer is told to install Tcl/Tk, it will install a separate copy of that library (and the corresponding _tkinter and tkinter etc.) for that Python installation. On Linux, Tcl/Tk will normally come with Linux; packages like python3-tk will add a _tkinter that uses the system Tcl/Tk, and a tkinter package (which will naturally find and use the _tkinter implementation, using the normal import mechanism).

Since the Tcl/Tk installation is thus "vendored" for Windows, the Tcl/Tk version will depend on the Python version. On Linux it will depend on the system, and it should be possible to use the system package manager to upgrade Tcl/Tk independently of Python. Note in particular that newer versions of Python might not be able to work with an outdated system Tcl/Tk. (To check the Tcl/Tk version for a working installation, see How to determine what version of python3 tkinter is installed on my linux machine? .)

Gudrin answered 25/4, 2023 at 20:32 Comment(0)
S
3

Hopefully this helps others like me who use venv and have multiple python versions (e.g. 3.8, 3.9 and 3.10) side by side on the same system. Suppose you created your venv with a specific python version, and can't import tkinter:

$ python3.10 -m venv my_venv_1 #create a venv with python 3.10
$ source my_venv_1/bin/activate
$ python
Python 3.10.11 (main, Apr  5 2023, 14:15:10) [GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tkinter
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'tkinter'
>>> quit()
$ deactivate

You can specifically install tkinter for the python version that matches the python version of the venv you created before. For example on ubuntu, you then need to install tkinter for your existing system wide python 3.10 specifically with this command:

sudo apt-get install python3.10-tk

Now if you activate the venv that you already created, tkinter will be picked up automatically:

source my_venv_1/bin/activate
python
>>>import tkinter as tk
>>>

Success!

Supplicatory answered 30/4, 2023 at 21:48 Comment(0)
G
0

Special environments

This is a community wiki answer intended to round up answers for dealing with non-standard Python installations. Please edit to add information for them. To start off I am including some links for previous specific questions about these environments, whether or not they were suitably answered.

Abaqus

python3-dbg (debug build provided by gdb?)

QGIS

Enthought Canopy

Anaconda

PyPy

IronPython / Python.NET

Bundled executables created with PyInstaller etc.

Gudrin answered 25/4, 2023 at 20:32 Comment(0)
G
-1

Standard troubleshooting steps

Please make sure of the following before concluding that Tkinter needs to be installed somewhere.

  • Does it make sense in the first place, to try to use Tkinter in this program? In particular, web applications and similar client-server applications should generally not try to use any kind of desktop GUI toolkit on the server - Tkinter included. The server will often not have a physical display, and end users wouldn't be able to see it anyway; most server hosting will not include Tkinter etc. in their Python support on so-called "headless" servers.

    It also doesn't generally make sense to try to "send" a GUI to the client side this way. In a web app, data (HTML/CSS/Javascript) will be sent to the web browser which creates the UI there. For stand-alone programs that will send data to a server, the client should implement the GUI, and use its own logic to interpret data that was sent from the server in order to update the GUI widgets. It makes no sense for the server to try to "control" the application on the client.

    As a special note for Matplotlib and similar libraries that optionally display GUI content: it may not be necessary to use specifically Tkinter to see GUI results, and it may be possible to solve the problem without a GUI. In particular, Matplotlib can be told to use a non-GUI "backend" and then save graphs into image files rather than displaying them on screen (which is often more useful anyway). It can also be told to use other GUI backends besides Tkinter. For details, see:

  • Is the import spelled correctly for this version of Python? 2.x code must refer to Tkinter by default, but 3.x must refer to tkinter.

  • Which installation of Python is in use for the code? Just like with everything else that can go wrong with running the wrong Python (i.e.: wrong third-party libraries installed for that Python, version incompatible with the code), it's possible that some installations of Python on a given machine support Tkinter and others do not.

    Note especially on Linux that just because Tcl/Tk is installed on the system does not mean that every Python installation will have access to it. Tkinter support needs to be added to each installation.

    This can interact with the previous issue: suppose a given machine has both a 2.x and a 3.x version installed. Even if Tkinter is available for both, trying to run the code with the wrong version would cause an ImportError (assuming there isn't a SyntaxError first, from e.g. trying to use print as a statement in 3.x).

    If it's intentional that some Python installations don't support Tkinter on a given system, just make sure that the Tkinter code runs with an installation that supports Tkinter.

    Especially be aware that virtual environments count as separate Python installations. Generally, they will have Tkinter support if they were created from a base installation that had Tkinter support when the virtual environment was created. Generally it is not possible to add Tkinter support directly to a virtual environment. Keep in mind that other third-party tools - IDEs like PyCharm, build-toolchain tools like Poetry, and environment management tools like pyenv - may create virtual environments - read the documentation and make sure of how they work.

Gudrin answered 29/4, 2023 at 23:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.