Tkinter: "Python puede no estar configurado para Tk"


Hoy quería empezar a trabajar con Tkinter, pero tengo algunos problemas.

Python 3.2 (r32:88445, Mar 28 2011, 04:14:07) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from tkinter import *
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.2/tkinter/__init__.py", line 39, in <module>
import _tkinter # If this fails your Python may not be configured for Tk
ImportError: No module named _tkinter

Entonces, ¿cómo puedo configurar mi Python 3.2 para que funcione con Tkinter?

Author: Maciej Ziarko, 2011-03-28

11 answers

Según http://wiki.python.org/moin/TkInter :

Si falla con "Ningún módulo llamado _tkinter", su configuración de Python necesita ser modificada para incluir este módulo (que es un módulo de extensión implementado en C). Hacer no editar Módulos/Configuración (está desactualizado). Es posible que tenga que instalar Tcl y Tk (cuando use RPM, instale los RPMs-devel también) y / o edite el setup.py script para apuntar a las ubicaciones correctas donde está instalado Tcl / Tk. Si instala Tcl / Tk en las ubicaciones predeterminadas, simplemente volver a ejecutar "make" debería construir la extensión _tkinter.

 24
Author: Sandro Munda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-28 13:15:47

En Arch/Manjaro simplemente instale el paquete tk:

sudo pacman -S tk
 46
Author: Jabba,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-27 21:27:11

Instala tk-devel (o un paquete de nombre similar) antes de compilar Python.

 41
Author: Ignacio Vazquez-Abrams,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-28 13:14:36

Para que esto funcione con pyenv en Ubuntu 16.04, tuve que:

$ sudo apt-get install python-tk python3-tk tk-dev

Luego instala la versión de Python que quería:

$ pyenv install 3.6.2

Entonces podría importar tkinter muy bien:

import tkinter
 5
Author: PaulMest,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-10 19:42:34

Tuvo el mismo problema en Fedora con Python 2.7. Resulta que se requieren algunos paquetes adicionales:

sudo dnf install tk-devel tkinter

Después de instalar los paquetes, este ejemplo de hello-world parece estar funcionando bien en Python 2.7:

$ cat hello.py
from Tkinter import *
root = Tk()
w = Label(root, text="Hello, world!")
w.pack()
root.mainloop()
$ python --version
Python 2.7.8
$ python hello.py

Y a través del reenvío X11, se ve así:

Hola Mundo a través de X11

Tenga en cuenta que en Python 3, el nombre del módulo es en minúsculas, y es probable que se requieran otros paquetes...

from tkinter import *
 3
Author: Stefan Saru,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-12 15:39:00

Encontré este problema en python 2.7.9.
Para arreglarlo, instalé tk y tcl, y luego reconstruí el código python y reinstalé, y durante configure, establecí la ruta para tk y tcl explícitamente, de la siguiente manera:

./configure --with-tcltk-includes="-I/usr/include" --with-tcltk-libs="-L/usr/lib64 -ltcl8.5 -L/usr/lib64 -ltk8.5"

Además, un artículo completo para el proceso de instalación de python: Construyendo Python desde la fuente

 2
Author: dasons,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-22 06:07:48

Oh acabo de seguir la solución que Ignacio Vázquez-Abrams ha sugerido que es instalar tk-dev antes de construir python. (Construyendo Python-3.6.1 desde el código fuente en Ubuntu 16.04.)

Hubo objetos precompilados y binarios que tuve que construir ayer, sin embargo, no limpié los objetos y simplemente construí de nuevo en la misma ruta de construcción. Y funciona muy bien.

sudo apt install tk-dev
(On the python build path)
(No need to conduct 'make clean')
./configure
make
sudo make install

¡Eso es todo!

 1
Author: David Jung,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-22 00:42:22
sudo apt-get install python3-tk
 1
Author: Rafal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-23 14:37:27

Para cualquiera que use Windows y el Subsistema de Windows para Linux, asegúrese de que cuando ejecute el comando python desde la línea de comandos, no esté ejecutando accidentalmente la instalación de python desde WSL. Esto me ha dado un gran dolor de cabeza. Una comprobación rápida que puede hacer para esto es solo
which <python command you're using>
Si eso imprime algo como /usr/bin/python2 aunque estés en powershell, probablemente eso es lo que está pasando.

 1
Author: bbukaty,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-22 05:47:13

Creo que la respuesta más completa a esto es la respuesta aceptada que se encuentra aquí:

Cómo hacer que tkinter funcione con la instalación predeterminada de Python 2.7 de Ubuntu?

Me di cuenta después de mucho tiempo dedicado a este problema, así que espero poder ahorrarle a alguien más la molestia.

Encontré este informe de error antiguo considerado inválido que mencionaba el exacto problema que estaba teniendo, tuve Tkinter.py pero no pudo encontrar el módulo _tkinter: http://bugs.python.org/issue8555

Instalé el paquete tk-dev con apt-get, y reconstruí Python usando ./ configure, make y make install en el directorio Python2.7.3. Y ahora mi Python2. 7 puede importar Tkinter, yay!

Estoy un poco molesto porque el paquete tk-dev no se menciona en absoluto en la documentación de instalación de Python.... a continuación se muestra otro útil recursos sobre módulos faltantes en Python si, como yo, alguien debería descubre que faltan más que "tkinter".

 0
Author: mjp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:44

Este síntoma también puede ocurrir cuando una versión posterior de python (2.7.13, por ejemplo) se ha instalado en /usr/local/bin "junto a" la versión de lanzamiento de python, y luego una actualización posterior del sistema operativo (por ejemplo, Ubuntu 12.04 > > Ubuntu 14.04) no elimina el python actualizado allí.

Para arreglar esa compatibilidad, se debe

A) eliminar la versión actualizada de python en / usr / local / bin;

B) desinstalar python-idle2. 7; y

C) reinstalar python-idle2. 7.

 0
Author: s.w.s.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-13 00:50:17