uv: Can't use tkinter with new venv set up with uv


(Maintainer edit)

NOTE If you are still affected by this, try reinstalling the managed Python interpreter

python install --reinstall ...

uv venv
source .venv/bin/activate
python -c "from tkinter import Tk; window = Tk()" 

This gives me the error message:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/Users/dstansby/.local/share/uv/python/cpython-3.12.5-macos-aarch64-none/lib/python3.12/tkinter/__init__.py", line 2346, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
_tkinter.TclError: Can't find a usable init.tcl in the following directories: 
    /tools/deps/lib/tcl8.6 /Users/dstansby/.venv/lib/tcl8.6 /Users/dstansby/lib/tcl8.6 /Users/dstansby/.venv/library /Users/dstansby/library /Users/dstansby/tcl8.6.12/library /Users/tcl8.6.12/library



This probably means that Tcl wasn't installed properly.

I can successfully run python -c "from tkinter import Tk; window = Tk()" in a fresh conda environment, but when I install python on conda it also installs tk, so maybe that’s why it works? Maybe this isn’t an issue with uv?, but if anyone knows how to get this working I’d be very gateful!

uv 0.4.4 (Homebrew 2024-09-04) macOS

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 43
  • Comments: 35 (15 by maintainers)

Most upvoted comments

So… expanding on the workaround so it works on all platforms, doesn’t clobber existing env vars, might work with tk 8.7+, and doesn’t bother doing anything if tk is actually working already (given that just because you used uv to write your library there’s no guarantee it will be run using the standalone Python builds that uv uses)… we have something like this.

import tkinter
from os import environ
from pathlib import Path
from sys import base_prefix
import platform

if not ("TCL_LIBRARY" in environ and "TK_LIBRARY" in environ):
    try:
        tkinter.Tk()
    except tkinter.TclError:
        tk_dir = "tcl" if platform.system() == "Windows" else "lib"
        tk_path = Path(base_prefix) / tk_dir
        environ["TCL_LIBRARY"] = str(next(tk_path.glob("tcl8.*")))
        environ["TK_LIBRARY"] = str(next(tk_path.glob("tk8.*")))

def main():
    tk = tkinter.Tk()
    tk.mainloop()


if __name__ == "__main__":
    main()

You can uv python install --reinstall <version>

$ find .venv -name “tcl” $ # ?


What am I doing wrong?

Those are in python installation directory not in virtualenv, I’m not next to linux box but under windows:

(venvflon) PS C:\Users\mplichta\Projects\venvflon> uv python list          
cpython-3.13.0-windows-x86_64-none     C:\Users\mplichta\AppData\Roaming\uv\python\cpython-3.13.0-windows-x86_64-none\python.exe
cpython-3.12.7-windows-x86_64-none     <download available>

So, path would be: C:\Users\mplichta\AppData\Roaming\uv\python\cpython-3.13.0-windows-x86_64-none\tcl\tcl8.6

As workaroud you can use tkinker like:

from os import environ
from pathlib import Path
from sys import base_prefix

environ["TCL_LIBRARY"] = str(Path(base_prefix) / "tcl" / "tcl8.6")
environ["TK_LIBRARY"] = str(Path(base_prefix) / "tcl" / "tk8.6")
import tkinter as tk

To anyone stumbling on this in the future, the process that worked for my team is:

  1. Delete your .venv folder
  2. Run uv python install --reinstall <version> (e.g., uv python install --reinstall 3.10)
  3. Re-create the virtual environment: .venv

To test:

  1. Activate the virtual environment: source .venv/bin/activate
  2. Run python -m tkinter
  3. You should see a basic Tk popup window.

I’m not opposed to doing a similar thing here.

Since most people expect to use Tkinter that comes with the python, I guess including TCL_LIBRARY and TK_LIBRARY env path pointing to where uv installed python as @emcek described would be a good default solution? The uv can provide some override mechanism, like allowing use to specify custom path to these two environment variable in the .python_version file or maybe some other files? This way TCL should always work by default.

I tried @emcek method on Mac and the result is successful

from os import environ
from pathlib import Path
from sys import base_prefix

environ["TCL_LIBRARY"] = str(Path(base_prefix) / "lib" / "tcl8.6")
environ["TK_LIBRARY"] = str(Path(base_prefix) / "lib" / "tk8.6")

print(environ["TCL_LIBRARY"])
print(environ["TK_LIBRARY"])

from tkinter import *
from tkinter import ttk
root = 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()

However I have changed the path of TCL_LIBRARY and TK_LIBRARY a bit as for mac its “lib” instead of “tcl”, as pointed out by @astrojuanlu

Maybe uv can populate the two environmental variable by default?

This issue is closed. Is there a fix? I just tried this on Ubuntu, and python cannot find tkinter.

I use uv 0.5.30 and updated all the python installs. Still i get the following error: from tkinter import Variable, StringVar, IntVar, DoubleVar, BooleanVar ImportError: cannot import name ‘Variable’ from ‘tkinter’ (unknown location)

Is this related?

It’ll be available following a python-build-standalone release, then a uv release — probably relatively soon.

We don’t support using arbitrary archives yet.

Hmmm… my workaround above fixes tk, but when I try to use the tkagg backend for matplotlib things get broken again. I’ll do some more investigation.

from . import _tkagg ImportError: initialization failed

This issue is mentioned in #6893

Seems like Tkinter is just unusable for now.

Hmmm… my workaround above fixes tk, but when I try to use the tkagg backend for matplotlib things get broken again. I’ll do some more investigation.

from . import _tkagg ImportError: initialization failed

to maybe point others to a workaround, all you’d need to do is to export an env variable called TCL_LIBRARY pointing to the correct tcl directory. to figure the correct one out, I did the following:

ATTENTION: this assumes that your .venv is based on the default python available to uv and also that tcl is at version 8.6, so keep that in mind

#!/bin/bash

# Get the Python path
PYTHON_PATH=$(cd ~ && uv run which python)

# Extract the base path
BASE_PATH=$(dirname "$(dirname "$PYTHON_PATH")")

# Construct the TCL_LIBRARY path
TCL_LIBRARY="$BASE_PATH/lib/tcl8.6"

# Set the environment variable
export TCL_LIBRARY

# Print the set variable (for verification)
echo "TCL_LIBRARY has been set to: $TCL_LIBRARY"

for comfort I’ve then just put the var in my .env file which gets automatically loaded by .envrc (direnv) - which btw would totally be an appealing feature for uv to replicate 😛

For the record, rye did this https://github.com/astral-sh/rye/pull/233