2011-03-28 11 views
45

Hoy quería comenzar a trabajar con Tkinter, pero tengo algunos problemas.Tkinter: "Python puede no estar configurado para Tk"

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 trabajar con Tkinter?

+1

Aunque esto no responde directamente a su pregunta, si está buscando utilizar la última versión de Python en Linux, usar binarios precompilados (como ActivePython, que incluye Tkinter) ahorraría mucho tiempo. –

+0

Sí, ahora lo sé. :) –

+1

Cada distribución de Linux tiene un paquete oficial de Python. A menos que necesite algo específico, el uso de binarios de terceros en realidad se desalienta. Dicho esto, probablemente uno o dos comandos tengan soporte Tk en python, pero necesito saber qué sabor de Linux estás ejecutando. –

Respuesta

23

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

If it fails with "No module named _tkinter", your Python configuration needs to be modified to include this module (which is an extension module implemented in C). Do not edit Modules/Setup (it is out of date). You may have to install Tcl and Tk (when using RPM, install the -devel RPMs as well) and/or edit the setup.py script to point to the right locations where Tcl/Tk is installed. If you install Tcl/Tk in the default locations, simply rerunning "make" should build the _tkinter extension.

+0

¿Cómo edita el script setup.py? ¿Cómo vuelves a hacer? Estoy intentando hacer esto en un Mac y estoy descubriendo que debería devolver el mac y obtener una máquina de Windows. –

+2

En mi caso esto fue causado por una actualización de 'tk'. Solo fue utilizado por 'matplotlib', y puede ser circunnavegado: http://stackoverflow.com/a/4935945/1959808 –

+0

setup.py está ubicado en el directorio de código fuente de python – dasons

36

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

+18

En Ubuntu, ejecute 'sudo apt-get instale tk-dev ', y luego vuelva a ejecutar make – pycoder112358

+0

@ pycoder112358: Lo hice pero todavía me está diciendo 'ImportError: Ningún módulo llamado _tkinter' cuando intento importar tkinter. Utilizo python3.4.0 compilado de fuente en ubuntu 13.10. – ARF

+5

¿Qué es 'tk-devel' ? Debe dar al menos una explicación mínima de por qué debería ser útil en este caso. – nbro

3

tenían el mismo problema en Fedora con Python 2.7. Resulta que son necesarios algunos paquetes adicionales:

sudo dnf install tk-devel tkinter 

Después de instalar los paquetes, este hello-world ejemplo, parece estar funcionando muy 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 de la expedición X11, que se ve así:

Hello World through X11

Tenga en cuenta que en Python 3, el nombre del módulo es minúscula, y otros paquetes están a favor bably necesaria ...

from tkinter import * 
+0

sudo: dnf: comando no encontrado (Estoy ubuntu, ¿es esta la diferencia?) – mjp

33

bajo arco/Manjaro sólo tiene que instalar el paquete tk:

sudo pacman -S tk 
+0

¡Perfecto! El error que obtengo en Manjaro y que este corregido es: 'ImportError: libtk8.6.so: no se puede abrir el archivo de objeto compartido: No existe tal archivo o directorio'. – DJSquared

0

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

How to get tkinter working with Ubuntu's default Python 2.7 install?

I figured it out after way too much time spent on this problem, so hopefully I can save someone else the hassle.

I found this old bug report deemed invalid that mentioned the exact problem I was having, I had Tkinter.py, but it couldn't find the module _tkinter: http://bugs.python.org/issue8555

I installed the tk-dev package with apt-get, and rebuilt Python using ./configure, make, and make install in the Python2.7.3 directory. And now my Python2.7 can import Tkinter, yay!

I'm a little miffed that the tk-dev package isn't mentioned at all in the Python installation documentation.... below is another helpful resource on missing modules in Python if, like me, someone should discover they are missing more than _tkinter.

-1

Este síntoma también puede ocurrir cuando un ver sion of python (2.7.13, por ejemplo) se ha instalado en/usr/local/bin "junto a" la versión python de lanzamiento, y luego una actualización subsiguiente del sistema operativo (digamos, Ubuntu 12.04 -> Ubuntu 14.04) falla eliminar la python actualizada allí.

Para corregir esto imcompatibility, uno debe

a) eliminar la versión actualizada de pitón en// local/bin usr;

b) desinstale python-idle2.7; y

c) reinstalar python-idle2.7.

1

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

Hubo objetos precompilados y binarios He tenido compilación ayer sin embargo, no limpié los objetos y simplemente volví a construir en el mismo Construir camino. Y funciona maravillosamente.

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

Eso es todo!

0
sudo apt-get install python3-tk 
0

Para conseguir que esto funcione con pyenv en Ubuntu 16.04, que tenía que:

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

a continuación, instalar la versión de Python que quería:

$ pyenv install 3.6.2 

Entonces podría importar tkinter bien:

import tkinter 
0

Me encuentro con este problema en Python 2.7.9. solucionarlo, he instalado tk y TCL, y luego reconstruir el código Python y vuelva a instalar, y durante configure, que establecer la ruta de tk y TCL explícitamente, por

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

también, todo un artículo para el pitón proceso de instalación : Building Python from Source

Cuestiones relacionadas