No module named tkinter windows

ошибка matplotlib — нет модуля с именем tkinter

Я попытался использовать пакет matplotlib через PyCharm IDE в windows 10. когда я запускаю этот код:

Я получаю следующую ошибку:

Я знаю, что в Python 2.x он назывался Tkinter, но это не проблема — я только что установил новый python 3.5.1.

EDIT: кроме того, я также попытался импортировать «tkinter» и «Tkinter» — ни один из них не работал (оба вернули сообщение об ошибке, о котором я упоминал).

какие идеи? спасибо заранее

13 ответов:

Edit:

для Windows, я думаю, проблема в том, что вы не установили полный пакет Python. Поскольку Tkinter должен поставляться с Python из коробки. Смотрите: http://www.tkdocs.com/tutorial/install.html

Я предлагаю установить ipython, который обеспечивает мощную оболочку и необходимые пакеты.

на Centos имена пакетов и команды различны. Вам нужно будет сделать:

чтобы устранить проблему.

если вы не хотите использовать tkinter на всех.

также не забудьте использовать %matplotlib inline в верхней части вашего ноутбука, если он используется.

EDIT: agg — это другой бэкенд как tkinter для matplotlib.

Если вы используете fedora, то сначала установите tkinter

Я не думаю, что вам нужно импорт tkinter потом Я также предлагаю вам использовать virtualenv

и добавить необходимые пакеты с помощью pip

почти все ответы, которые я искал по этой проблеме, говорят, что Python на Windows поставляется с уже установленными tkinter и tcl, и мне не удалось загрузить или установить их с помощью pip, или actviestate.com сайт. В конце концов я обнаружил, что когда я устанавливал python с помощью двоичного установщика, я снял флажок с модуля, связанного с TCL и tkinter. Итак, я снова запустил двоичный установщик и решил изменить свою версию python к этому времени, выбрав эту опцию. Не нужно ничего делать вручную затем. Если вы перейдете на свой терминал python, то следующие команды должны показать вам версию tkinter, установленную с вашим Python:

на CentOS 7 и Python 3.4, команда sudo yum install python34-tkinter

на Redhat 7.4 с Python 3.6, команда sudo yum install rh-python36-python-tkinter

на Ubuntu, в начале 2018 года, нет python3.6-tk на ubuntu (xenial/16.04) нормальные дистрибутивы, так что даже если у вас есть более ранние версии python-tk это не будет работать.

мое решение было использовать set everything up with python 3.5 :

и теперь matplotlib можете найти tkinter .

EDIT:

мне просто нужно было 3.6 В конце концов, и трюк был:

а затем перестроить python3. 6,после tk-dev , например:

на CentOS 6.5 с python 2.7 мне нужно было сделать: yum install python27-tkinter

для пользователей windows повторно запустите программу установки. Выберите Изменить. Установите флажок для tcl / tk и простоя. Описание для этого говорит «устанавливает tkinter»

Если вы используете python 3.6, это сработало для меня:

который работает для других версий python3

иногда (например, в дистрибутиве osgeo4w) Tkinter удаляется.

попробуйте изменить matplotlib backend editing matplotlibrc расположенном в [python install dir]/matplotlib/mpl-data/matplotlibrc изменение backend

на Windows пользователи, Нет необходимости загружать установщик снова. Просто сделайте следующее:

  1. перейдите в меню Пуск, введите программы и компоненты,
  2. выберите версию Python (для меня это Python 3.6.5 (64-бит)),
  3. правой кнопкой мыши, нажмите клавишу изменить,
  4. клик изменить,
  5. выберите td / tk и простоя (который устанавливает tkinter) и нажмите кнопку далее.

подождите установки, и вы сделали.

Так как я использую Python 3.7 на Ubuntu я должен был использовать:

ModuleNotFoundError: нет модуля с именем tkinter при импорте matplotlib Python 3.6 (x64) [duplicate]

Ошибки округления с плавающей запятой. 0,1 не могут быть представлены точно в базе-2, как в базе-10, из-за недостающего простого коэффициента 5. Так же, как 1/3 принимает бесконечное число цифр для представления в десятичной форме, но составляет «0,1» в базе-3, 0.1 принимает бесконечное число цифр в базе-2, где оно не находится в базе-10. И компьютеры не имеют бесконечного объема памяти.

Читайте также:  Windows 10 перестала работать тачпад

13 ответов

Для Windows, я думаю, проблема в том, что вы не установили полный пакет Python. Так как Tkinter должен быть отправлен с Python из коробки. Смотрите: http://www.tkdocs.com/tutorial/install.html

Я предлагаю установить ipython , который обеспечивает мощную оболочку и необходимые пакеты также.

Если вы используете python 3.6, это сработало для меня:

Что работает для других версий python3

Иногда (например, в дистрибутиве osgeo4w) tkinter удаляется.

Попробуйте изменить редактирование базы данных matplotlib matplotlibrc файл, расположенный в [python install dir]/matplotlib/mpl-data/matplotlibrc изменении. Бэкэнд от backend: TkAgg к чему-то другому, подобному backend: Qt4Agg , как описано здесь: http://matplotlib.org/faq/usage_faq.html#what-is-a-backend

Для пользователей Windows нет необходимости снова загружать установщик. Просто выполните следующие действия:

  1. Перейдите в меню «Пуск», введите «Программы и функции»,
  2. Выберите версию Python (для меня это Python 3.6.5 (64-разрядная версия)). ,
  3. Щелкните правой кнопкой мыши, нажмите «Изменить»,
  4. Нажмите «Изменить»,
  5. Выберите td / tk и IDLE (который устанавливает tkinter) и нажмите «Далее».

Подождите, пока вы закончите установку.

В CentOS 7 и Python 3.4 команда sudo yum install python34-tkinter

В Redhat 7.4 с Python 3.6 команда sudo yum install rh-python36-python-tkinter

Почти все ответы, которые я искал в этой проблеме, говорят о том, что Python в Windows поставляется с уже установленными tkinter и tcl, и мне не удавалось загружать или устанавливать их с помощью pip или сайта actviestate.com. В итоге я обнаружил, что когда я устанавливал python с помощью двоичного установщика, я отключил модуль, связанный с TCL и tkinter. Итак, я снова запустил двоичный установщик и решил изменить мою версию python, выбрав этот вариант. Тогда не нужно ничего делать вручную. Если вы перейдете на свой терминал python, то следующие команды должны показать вам версию tkinter, установленную с вашим Python:

Поскольку я использую Python 3.7 на Ubuntu, мне пришлось использовать:

В Ubuntu в начале 2018 года нет python3.6-tk в нормальных дистрибутивах ubuntu (xenial / 16.04), поэтому даже если у вас более ранние версии python-tk , это не сработает.

My решение должно было использовать все с помощью python 3.5 :

И теперь matplotlib может найти tkinter .

I просто нужно было 3.6 afterall, а трюк был:

, а затем перестроить python3.6, после tk-dev , например:

вы можете использовать

, если вы вообще не хотите использовать tkinter .

Также не забудьте использовать %matplotlib inline в верхней части вашего ноутбука, если с помощью одного.

EDIT: agg — другой бэкэнд, такой как tkinter для matplotlib.

Для пользователей Windows запустите программу установки. Выберите «Изменить». Установите флажок для tcl / tk и IDLE. В описании для этого говорится: «Устанавливает tkinter»

В Centos имена и команды пакетов различны. Вам нужно будет сделать:

Чтобы устранить проблему.

Если вы используете fedora, тогда сначала установите tkinter

Я не думаю, что вам нужно импортировать tkinter после этого, я также предлагаю вам использовать virtualenv

И добавьте необходимые пакеты, используя pip

На CentOS 6.5 с python 2.7 мне нужно было сделать: yum install python27-tkinter

matplotlib error — no module named tkinter

I tried to use the matplotlib package via Pycharm IDE on windows 10. when I run this code:

I get the following error:

I know that in python 2.x it was called Tkinter, but that is not the problem — I just installed a brand new python 3.5.1.

EDIT: in addition, I also tried to import ‘tkinter’ and ‘Tkinter’ — neither of these worked (both returned the error message I mentioned).

17 Answers 17

For Linux

Debian based distros:

RPM based distros:

For windows:

For Windows, I think the problem is you didn’t install complete Python package. Since Tkinter should be shipped with Python out of box. See: http://www.tkdocs.com/tutorial/install.html . Good python distributions for Windows can be found by the companies Anaconda or ActiveState.

Test the python module

p.s. I suggest installing ipython, which provides powerful shell and necessary packages as well.

if you dont want to use tkinter at all.

Also dont forget to use %matplotlib inline at the top of your notebook if using one.

EDIT: agg is a different backend like tkinter for matplotlib.

Читайте также:  Компьютере недоступна служба установщика модулей windows

For Windows users, there’s no need to download the installer again. Just do the following:

  1. Go to start menu, type Apps & features,
  2. Search for «python» in the search box,
  3. Select the Python version (e.g. Python 3.8.3rc1(32-bit)) and click Modify,
  4. On the Modify Setup page click Modify,
  5. Tick td/tk and IDLE checkbox (which installs tkinter) and click next.

Wait for installation and you’re done.

On Centos, the package names and commands are different. You’ll need to do:

To fix the problem.

Almost all answers I searched for this issue say that Python on Windows comes with tkinter and tcl already installed, and I had no luck trying to download or install them using pip, or actviestate.com site. I eventually found that when I was installing python using the binary installer, I had unchecked the module related to TCL and tkinter. So, I ran the binary installer again and chose to modify my python version by this time selecting this option. No need to do anything manually then. If you go to your python terminal, then the following commands should show you version of tkinter installed with your Python:

If you are using fedora then first install tkinter

I don’t think you need to import tkinter afterwards I also suggest you to use virtualenv

And add the necessary packages using pip

On CentOS 7 and Python 3.4, the command is sudo yum install python34-tkinter

On Redhat 7.4 with Python 3.6, the command is sudo yum install rh-python36-python-tkinter

For windows users, re-run the installer. Select Modify. Check the box for tcl/tk and IDLE. The description for this says «Installs tkinter»

On Ubuntu, early 2018, there is no python3.6-tk on ubuntu’s (xenial/16.04) normal distributions, so even if you have earlier versions of python-tk this won’t work.

My solution was to use set everything up with python 3.5 :

And now matplotlib can find tkinter .

EDIT:

I just needed 3.6 afterall, and the trick was to:

and then rebuild python3.6, after tk-dev , eg:

No module named Tkinter

I have a small script in python2.7 that I want to convert into Windows executable. I use pyinstaller for this.

Basically, the script just plots a point on a grid.

The converting process finishes successfully. When I run the .exe however I’ve got the ImportError (see below) even though I have no reference to Tkinter anywhere.

What could went wrong here?

2 Answers 2

I have a feeling that matplotlib uses the Tkinter module internally, but imports it in a non-standard way. Then pyinstaller doesn’t notice Tkinter is needed, and subsequently doesn’t bundle it into the executable.

Try explicitly putting import Tkinter at the top of your script.

I had the same issue and none of the solutions here worked. I was using Pyinstaller 3.2 (the latest version at the time) and everything was fixed (and no import statements needed) when I upgraded to the latest developer version using

This seems to indicate that at the times of writing this that all the kinks to this issue are still being worked out

EDIT: As of January 15 2017 Pyinstaller version 3.2.1 was released. I now use this and it solves this issue along with others like this and this that I could previously only solve by using the developer version. So I highly recommend upgrading to the latest version if you haven’t already.

ModuleNotFoundError: No module named ‘tkinter’ #92022 #10433

Comments

nidamanx commented Mar 4, 2020

The text was updated successfully, but these errors were encountered:

brettcannon commented Mar 4, 2020

Unfortunately there is not enough detail to debug your issue, but based on your traceback it looks like you’re on Linux. If you happen to be using Ubuntu, know that tkinter is not included with the system install and you will need to apt-get it separately.

nidamanx commented Mar 5, 2020

Yes, I’m on Linux (Debian 10).
All is correctly installed and tkinter works perfectly everywhere else and with otther IDEs

No way to use tkinter with this plugin (using gui or terminal integrated in vscode)
Which detailed information do you need to better check this bug?

brettcannon commented Mar 5, 2020

We don’t manipulate imports in any way so chances are you selected a Python environment/interpreter in VS Code which doesn’t have tkinter installed. Check that the Python interpreter down in the status bar matches what you expect.

Читайте также:  Windows для нетбука samsung n145 plus

nidamanx commented Mar 6, 2020

I believe so and I tried many times on differnt venv and on OS environment.
Probably the problem is related on the way i decided to install vscode-oss. I used Flatpak.

brettcannon commented Mar 6, 2020

Does it work if you import tkinter in the REPL of the Python interpreter specified in «python.pythonPath» ? If it fails does the exact same interpreter succeed in the import in the terminal outside of VS Code?

nidamanx commented Mar 9, 2020 •

Install software on real Debian 10 machine

Create TkInter test file

Run from Debian terminal (python3_env activated)

/VEs/python3_env/tkinter_test.py
result: OK

Run from VSCode-OSS terminal (python3_env activated)

test python file
(python3_env) sh-5.0$ python3

/VEs/python3_env/tkinter_test.py
result: FAIL
ModuleNotFoundError: No module named ‘tkinter’

Run from VSCode-OSS GUI (python3_env selected and activated)

result: FAIL
ModuleNotFoundError: No module named ‘tkinter

Get python path from VSCode-OSS Terminal using virtual environment

check python sys.path and tkinter import

result: FAIL

brettcannon commented Mar 9, 2020

There’s a Python version discrepancy there. In your first example it’s Python 3.7.3 but in all your other examples it’s 3.7.4 which suggests you’re using two different interpreters. That would explain why in one case you have tkinter installed and in all the others you do not.

You can also import tkinter in the case where it’s succeeding, print out tkinter.__file__ and then print out sys.path on the environment that’s failing to see if that path is being set.

nidamanx commented Mar 10, 2020

Oh, you’re right! That’s really strange.
It seems VSCode-OSS cannot see what the system installed using venv
I decided a double check installing Virtual Enviromnent in the old way

From Debian Terminal

From VSCode-OSS Terminal

And now they match!
Really strange.
Anyway, even without that issue, TkInter still cannot be found.
After run the script (I provided in the last post) I got the same error.
Here is the result from the VSCode-OSS Terminal

And now the results about the path (sys and tkinter)

From Debian Terminal:

From VSCode-OSS Terminal:

Conclusion:
I have to say I tried also another IDE (same script and same Virtual Environment) and all was fine.
It’s a pity because I would like to use VSCode-OSS
By the way TkInter fails even without Virtual Environments

Thanks for your time and I hope we will find where how to solve.
I will keep you informed in case of success

brettcannon commented Mar 10, 2020

Why are the prompts different? In your Debian example it’s user@pc:

$ and in the test example it’s sh-5.0$ . Are you using different shells in each case?

You can also try running Python with -v to get verbose import logging to see if any differences show up there. Lastly, you can try setting «terminal.integrated.inheritEnv»: false to try a more clean environment.

And what is «VSCode-OSS»? Are you using a fork of VS Code?

nidamanx commented Mar 11, 2020 •

Why are the prompts different? In your Debian example it’s user@pc:

$ and in the test example it’s sh-5.0$ . Are you using different shells in each case?

No. The first is the OS Terminal, the second is the tetminal inside vscode. I change nothing from the original vscode settings.
I’m using bash in my OS and it seems VSCode is using sh (I tryed to change to bash in VSCode too, but same result.

you can try setting «terminal.integrated.inheritEnv»: false

in that way I disabled the terminal inside vscode. but still the same issue

And what is «VSCode-OSS»? Are you using a fork of VS Code?

No fork. Name taken just from the following link and from the header of the installed software itself «Visual Studio code — OSS»
https://github.com/microsoft/vscode#visual-studio-code—open-source-code—oss

You can also try running Python with -v to get verbose import logging

After activating veng in OS and VSCode, the return was totally the same

This is a very strange issue
I can only ask if there is an official way to install on Linux. Maybe the problem is really there.
I used flatpak (I took the OSS)
https://flathub.org/apps/search/visual%20studio%20code

Thanks for your time.
And, if I’m the only one with this issue, feel free to close the ticket.
If I will find a way, I will share here.
Meanwhile I could migrate to wxPython (that is LGPL, so also fine for my use)

Оцените статью