No module named tkinter ошибка

For some reason, I can’t use the Tkinter (or tkinter, on Python 3) module.
After running the following command in the python shell:

import Tkinter

or this, in Python 3:

import tkinter

I got this error

ModuleNotFoundError: No module named ‘Tkinter’

or this:

ModuleNotFoundError: No module named ‘tkinter’

What could be the reason for these errors and how can I solve it?

Ben the Coder's user avatar

asked Sep 18, 2014 at 6:19

RasmusGP's user avatar

0

You probably need to install it using something similar to the following:

  • For Ubuntu or other distros with Apt:

    sudo apt-get install python3-tk
    
  • For Fedora:

    sudo dnf install python3-tkinter
    

You can also mention a Python version number like this:

  • sudo apt-get install python3.7-tk
    
  • sudo dnf install python3-tkinter-3.6.6-1.fc28.x86_64
    

Finally, import tkinter (for Python 3) or Tkinter (for Python 2), or choose at runtime based on the version number of the Python interpreter (for compatibility with both):

import sys
if sys.version_info[0] == 3:
    import tkinter as tk
else:
    import Tkinter as tk

Mark Amery's user avatar

Mark Amery

144k81 gold badges406 silver badges459 bronze badges

answered Sep 18, 2014 at 6:26

d-coder's user avatar

d-coderd-coder

12.9k4 gold badges26 silver badges36 bronze badges

6

As you are using Python 3, the module has been renamed to tkinter, as stated in the documentation:

Note Tkinter has been renamed to tkinter in Python 3. The 2to3 tool
will automatically adapt imports when converting your sources to
Python 3.

answered Sep 18, 2014 at 6:27

Burhan Khalid's user avatar

Burhan KhalidBurhan Khalid

170k18 gold badges245 silver badges284 bronze badges

0

If you’re using python 3.9 on Mac, you can simply install tkinter using brew:

brew install python-tk@3.9

This fixed it for me.

Edit:
As mentioned by others, you can also use the general command to install the latest version:

brew install python-tk

answered Apr 10, 2021 at 18:11

P1NHE4D's user avatar

P1NHE4DP1NHE4D

1,14610 silver badges14 bronze badges

0

For windows 10, it is important to check in the Python install the optional feature «tcl/tk and IDLE». Otherwise you get a ModuleNotFoundError: No module named ‘tkinter’. In my case, it was not possible to install tkinter after the Python install with something like «pip install tkinter»

answered Jan 29, 2020 at 15:43

Andi Schroff's user avatar

Andi SchroffAndi Schroff

1,1561 gold badge12 silver badges18 bronze badges

3

To install the Tkinter on popular Linux distros:

Debian/Ubuntu:

sudo apt install python3-tk -y  

Fedora:

sudo dnf install -y python3-tkinter

Arch:

sudo pacman -Syu tk --noconfirm 

REHL/CentOS6/CentOS7:

sudo yum install -y python3-tkinter

OpenSUSE:

sudo zypper in -y python-tk

bfontaine's user avatar

bfontaine

18.2k13 gold badges73 silver badges107 bronze badges

answered Feb 20, 2021 at 13:31

amzy-0's user avatar

amzy-0amzy-0

4354 silver badges5 bronze badges

5

For Mac use:

brew install python-tk

imxitiz's user avatar

imxitiz

3,9203 gold badges9 silver badges33 bronze badges

answered Jan 21, 2022 at 21:24

Diego Medeiros's user avatar

0

You might need to install for your specific version, I have known cases where this was needed when I was using many versions of python and one version in a virtualenv using for example python 3.7 was not importing tkinter I would have to install it for that version specifically.

For example

sudo apt-get install python3.7-tk 

No idea why — but this has occured.

answered May 20, 2020 at 17:31

deMangler's user avatar

deManglerdeMangler

4273 silver badges14 bronze badges

0

Installing Tkinter

python -m pip install tk-tools

or

sudo apt install python3-tk

answered Sep 26, 2021 at 13:11

Mr.Programmer nope's user avatar

3

For Windows 10 using either VSCode or PyCharm with Python 3.7.4 — make sure Tk is ticked in the install. I tried import tkinter as xyz with upper/lower t and k‘s and all variants without luck.

What works is:

import tkinter
import _tkinter
tkinter._test()

An example in action:

import tkinter
import _tkinter

HEIGHT = 700
WIDTH = 800

root = tkinter.Tk()

canvas = tkinter.Canvas(root, height = HEIGHT, width=WIDTH)
canvas.pack()

frame = tkinter.Frame(root, bg='red')
frame.pack()

root.mainloop()

answered Sep 7, 2019 at 3:29

Jeremy Thompson's user avatar

Jeremy ThompsonJeremy Thompson

62.1k36 gold badges195 silver badges322 bronze badges

5

check the python version you have installed by using command python --version

check for the Tk module installed correctly from following code

sudo apt-get install python3-tk 

Check if you are using open-source OS then

check the tkinter module in the following path
/home/python/site-packages/tkinter
change the path accordingly your system

barbsan's user avatar

barbsan

3,42811 gold badges21 silver badges28 bronze badges

answered Jul 24, 2019 at 9:56

Devaliya Pratik's user avatar

On CentOS7, to get this working with Python2, I had to do:

yum -y install tkinter

Noting this here because I thought that there would be a pip package, but instead, one needs to actually install an rpm.

answered Feb 3, 2020 at 19:57

Frederick Ollinger's user avatar

Make sure that when you are running your python code that it is in the python3 context. I had the same issue and all I had to do was input the command as:

sudo python3 REPLACE.py

versus

sudo python REPLACE.py

the latter code is incorrect because tkinter is apparently unnavailable in python1 or python2.

answered Nov 28, 2019 at 20:42

Owen Preece's user avatar

3

You just need to install it and import them your project like that :

this code import to command line :

sudo apt-get install python3-tk 

after import tkinter your project :

from tkinter import *

answered Dec 8, 2019 at 6:33

Jafar Choupan's user avatar

1

I resolved my issue in the PyCharm do following

  1. Install Python Interpreter from https://www.python.org/
  2. PyCharm > Preferences > Python Interpreter > Add
  3. Select installed interpreter
  4. In the run configuration select the newly installed interpreter

I also made a video instruction what I did https://youtu.be/awaURBnfwxk

answered Nov 25, 2021 at 15:50

Dima Portenko's user avatar

Dima PortenkoDima Portenko

3,4735 gold badges35 silver badges48 bronze badges

$ sudo apt-get install python3.10-tk

answered Jan 14, 2022 at 10:20

Udesh's user avatar

UdeshUdesh

2,4452 gold badges22 silver badges32 bronze badges

For Windows I had to reinstall python and make sure that while installing in Optional Features I had «tcl/tk and IDLE» enabled.

answered Sep 2, 2022 at 15:45

Sout parl's user avatar

Tkinter should come with the latest Python, I don’t think it comes with Python2. I had the same problem but once. I upgraded to Python 3.8 Tkinter was installed.

Sabito stands with Ukraine's user avatar

answered Jun 10, 2020 at 14:14

Eloni's user avatar

EloniEloni

294 bronze badges

tkinter comes with python… uninstall python, reinstall it, you’re done

answered Apr 12, 2020 at 5:54

PythonProgrammi's user avatar

PythonProgrammiPythonProgrammi

22.4k3 gold badges41 silver badges34 bronze badges

0

if it doesnot work in pycharm you can add the module in the project interpreter by searching in +button python-tkinter and download it.

answered Jul 12, 2020 at 4:27

santosh ghimire's user avatar

Check apt for tasks, it may be marked for removed

sudo apt autoremove

Then check and install needed

answered Apr 23, 2020 at 6:02

Sergey Shamanayev's user avatar

We can use 2 types of methods for importing libraries

  1. work with import library
  2. work with from library import *

You can load tkinter using these ways:

  1. from tkinter import*

  2. import tkinter

Delrius Euphoria's user avatar

answered May 5, 2021 at 11:16

رضا آلناصر's user avatar

On Linux it is possible to have installed two different versions of Python in my case 3.11 and 3.10. Only 3.10 was working with tkinter. 3.10 binary was located in my /usr/bin/python3 and 3.11 was located in /usr/local/sbin/python3. You can either specifically source the version you need or if you are SURE you don’t need 3.11 at the moment, you can sudo cp /usr/bin/python3 /usr/local/sbin/python3 assuming your working version is in bin like mine is.

answered Mar 3 at 2:03

Poseidon's user avatar

PoseidonPoseidon

1651 silver badge8 bronze badges

try:
    # for Python2
    from Tkinter import *   ## notice capitalized T in Tkinter 
except ImportError:
    try:
        # for Python3
        from tkinter import *   ## notice lowercase 't' in tkinter here
    except:
        try:
            print "Download Tkinter" ##python 2
        except SyntaxError:
            print("Download Tkinter") ##python 3

answered Mar 31, 2021 at 2:43

Rodrigo Alvaro Santo SD 6's user avatar

0

If you have pip on your path, you could (in your command prompt) just type
pip install tkinter
Most versions of python already come with tkinter.

answered Feb 8, 2022 at 20:40

GL32's user avatar

GL32GL32

361 silver badge1 bronze badge

1

You’ll probably need to install Tkinter.
You can do so like this in the Windows command prompt:

pip install tk

answered Jan 25 at 6:26

AngusAU293's user avatar

——— WORKED ON PYTHON 2.7————

Install all below packages

sudo apt-get install git
sudo apt-get install python-tk
sudo apt-get install python-pip
sudo apt install picolisp
sudo -H pip2 install --upgrade pip
sudo pip install -I pillow
sudo apt-get install python-imaging-tk
sudo apt-get install python-tk

answered May 4, 2020 at 11:11

RAHUL 's user avatar

RAHUL RAHUL

235 bronze badges

1

Firstly you should test your python idle to see if you have tkinter:

import tkinter

tkinter._test()

Trying typing it, copy paste doesn’t work.

So after 20 hours of trying every way that recommended on those websites figured out that you can’t use «tkinter.py» or any other file name that contains «tkinter..etc.py». If you have the same problem, just change the file name.

fcdt's user avatar

fcdt

2,3815 gold badges15 silver badges27 bronze badges

answered Sep 20, 2020 at 9:38

Mehmet Nergiz's user avatar

cmd — terminal

pip install tkinter

answered Jan 22, 2022 at 9:10

Egemen İm's user avatar

1

Если вы столкнулись с ошибкой «ModuleNotFoundError: нет модуля с именем« tkinter »» во время работы над проектом или скриптом Python, вы не одиноки. Многие разработчики Python сталкивались с этой ошибкой, которая указывает на то, что в вашей установке Python отсутствует модуль tkinter. К счастью, решить эту ошибку относительно просто.

Tkinter — это стандартный пакет GUI (графический пользовательский интерфейс) для Python, который поставляется со стандартной библиотекой Python. Tkinter предоставляет простой способ создания приложений с графическим интерфейсом, которые работают в большинстве операционных систем, включая Windows, Linux и macOS. С помощью tkinter разработчики могут создавать окна, кнопки и другие элементы графического интерфейса, с которыми могут взаимодействовать пользователи.

Причины ошибки «ModuleNotFoundError: нет модуля с именем« tkinter »»

Ошибка «ModuleNotFoundError: нет модуля с именем« tkinter »» может быть вызвана несколькими причинами, в том числе:

  • Отсутствует модуль tkinter в вашей установке Python
  • Неправильно установленная или устаревшая версия Python
  • Неверная переменная среды PATH
  • Установка Python, которая не была добавлена ​​в системный PATH
  • Конфликт между несколькими установками Python на вашем компьютере

Как решить ошибку «ModuleNotFoundError: нет модуля с именем« tkinter »»

Ниже приведены решения для ошибки «ModuleNotFoundError: нет модуля с именем« tkinter »»:

Решение № 1. Проверьте, установлен ли tkinter

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

import tkinter

Войти в полноэкранный режимВыйти из полноэкранного режима

Если в вашей системе установлен tkinter, модуль будет успешно импортирован, и вы не увидите ошибку «ModuleNotFoundError: нет модуля с именем« tkinter »». Однако, если tkinter не установлен, вы увидите ошибку.

Решение № 2. Установите tkinter

Если tkinter не установлен в вашей системе, вам необходимо его установить. Вы можете установить tkinter с помощью диспетчера пакетов вашей операционной системы, такого как apt-get или yum, или с помощью диспетчера пакетов pip.

В Windows

Если вы используете Windows, tkinter поставляется с предустановленным Python. Однако, если по какой-то причине tkinter не установлен, вы можете установить его с помощью следующей команды:

pip install tkinter

Войти в полноэкранный режимВыйти из полноэкранного режима

В Linux

В Linux вы можете установить tkinter с помощью apt-get, yum или диспетчера пакетов вашей системы. Например, в Ubuntu вы можете установить tkinter с помощью следующей команды:

sudo apt-get install python3-tk

Войти в полноэкранный режимВыйти из полноэкранного режима

Решение № 3. Переустановите Python

Если первые два решения не сработали, вам может потребоваться переустановить установку Python. Убедитесь, что вы загрузили и установили последнюю версию Python с официального веб-сайта Python, чтобы избежать проблем при установке пакетов. Вы можете загрузить последнюю версию Python по следующему URL-адресу:

Решение № 4. Обновите версию Python

Если вы используете устаревшую версию Python, вы можете столкнуться с ошибками при установке или запуске пакетов, в том числе с ошибкой «ModuleNotFoundError: No module named tkinter». Убедитесь, что вы используете последнюю стабильную версию Python, чтобы избежать проблем.

Решение № 5. Проверьте переменную среды PATH

Убедитесь, что каталог установки Python добавлен в переменную среды PATH вашей операционной системы. Переменная PATH сообщает вашей операционной системе, где найти Python при выполнении команд Python или запуске сценариев.

В Windows

Чтобы проверить переменную среды PATH в Windows, выполните следующие действия:

  1. Откройте меню «Пуск» и найдите «Переменные среды».
  2. Нажмите «Изменить системные переменные среды».
  3. Нажмите кнопку «Переменные среды».
  4. В разделе «Системные переменные» найдите переменную «ПУТЬ» и нажмите «Изменить».
  5. Убедитесь, что каталог установки Python добавлен в переменную PATH. Если это не так, нажмите кнопку «Создать» и добавьте его.

В Linux

Чтобы проверить переменную среды PATH в Linux, вы можете запустить следующую команду в своем терминале:

echo $PATH

Войти в полноэкранный режимВыйти из полноэкранного режима

Если ваш каталог установки Python не включен в список, вы должны добавить его в переменную PATH.

Решение № 6. Проверьте наличие нескольких установок Python

Если на вашем компьютере установлено несколько установок Python, возможно, в одной установке есть tkinter, а в другой — нет. Убедитесь, что вы используете правильную установку Python с установленным tkinter.

Решение № 7. Используйте виртуальную среду

Использование виртуальной среды может помочь избежать конфликтов между различными установками Python и установленными пакетами. Это также может помочь управлять зависимостями пакетов и гарантировать, что ваше приложение или сценарий работают правильно. Убедитесь, что вы создали виртуальную среду, в которой установлен tkinter, или установите tkinter в виртуальной среде.

Заключение

Ошибка «ModuleNotFoundError: нет модуля с именем« tkinter »» в Python может быть вызвана несколькими причинами, включая отсутствие модуля tkinter, неправильную установку или версию Python, ошибочную переменную среды PATH или конфликты между несколькими установками Python на вашем компьютере. К счастью, решить эту ошибку относительно просто, и описанные выше решения должны устранить проблему. С правильно установленным модулем tkinter вы можете легко создавать приложения и интерфейсы с графическим интерфейсом.

In this article, we will discuss the solutions to resolve the error modulenotfounderror: no module named ‘tkinter’.

What is a tkinter?

The ‘_tkinter‘ module is a built-in Python module that provides a Python interface to the Tk GUI toolkit.

It is regularly included with Python installations in most platforms.

Some operating systems may require additional installation steps to make sure that the module is available.

Why modulenotfounderror: no module named tkinter occur?

The error message “ModuleNotFoundError: No module named ‘_tkinter’” occurs because if you try to import the ‘_tkinter‘ module in Python yet the module cannot find in your system.

What are the causes of the error no module named tkinter?

The cause of the error no module named tkinter is that the module tkinter is not installed in the python library.

Let’s have a look at the cause of the error in a different platform of operating systems.

The reasons of the error no module named _tkinter occurs on MacOS

The error “no module named tkinter” usually occurs on macOS when you are trying to run a Python script.

That uses the Tkinter library, which is a built-in library in Python that allows for the development of graphical user interfaces.

Here are the few reasons why this error may occur on macOS:

  • Python version: The older versions of macOS with a pre-installed version of Python 2, which could not include the Tkinter module. When you are using Python 3 and the script requires Tkinter, you need to install it separately.
  • Python installation: When you installed Python from a package like Homebrew or MacPorts, it is not included the Tkinter library. In this situation, you should reinstall the Python with Tkinter support.
  • Virtual environment: When you are using a virtual environment for your Python project, it does not include the Tkinter library installed. You can install it through running the command “pip install tkinter” in your python virtual environment.

The reasons of the error no module named tkinter occurs on Windows

The error “ModuleNotFoundError: No module named ‘_tkinter’” on Windows will occur due to the following reasons:

  • Missing or incomplete installation: When you are using a version of Python which does not include the tkinter module or it is not installed properly, so that’s why you may encounter this error.
  • Incorrect Python version: When you are using a 64-bit version of Python and a 32-bit version of Tcl/Tk or vice versa, the _tkinter module cannot find the required file, so that’s why you may encounter this error.

The reasons of the error no module named ‘tkinter’ occurs on Linux

The error “ModuleNotFoundError: No module named ‘_tkinter’” generally occurs on Linux if the tkinter module is not installed or it is not properly configured on your computer.

How to solve the modulenotfounderror: no module named tkinter?

Here are the solutions to solve the no module named tkinter python different platform in operating systems.

Solution 1: Install Tkinter module on Windows operating system

To install the Tkinter module on Windows, you can follow the following steps below:

Step 1: Open a web browser and go to the Python website at https://www.python.org/downloads/.

Python Website Modulenotfounderror: no module named _tkinter

Step 2: Click the “Download Python” button and download the latest version of Python for Windows.

Step 3: Once the download is complete, run the installer and follow the instructions to install Python on your computer.

Step 4: After that, check the tcl/tk and IDLE checkbox to install tkinter for your Python version.

Step 5: Type “pip install tkinter” in the command prompt and press Enter. It will download and install the Tkinter module on your computer.

Step 6: Ensure to check the following options when you get prompted:

  • tcl/tk and IDLE (installs tkinter and the IDLE development environment)
  • Install launcher for all users (recommended)
  • Add Python to PATH (this adds Python to your PATH environment variable)
  • Install the standard library test suite

Step 7: Once the installation is complete, you can open a Python shell and import the Tkinter module by typing “import tkinter” and pressing Enter.

import tkinter

That’s it! You should now be able to use Tkinter in your Python programs.

Solution 2: Install Tkinter module on MacOS operating system

Here are the steps to solve error no module name ‘tkinter’ on MacOS operating system.

Step 1: Check if Tkinter is installed: Open a terminal window and type the following command:

python -m tkinter

This command will execute a simple Tkinter window. When you get an error message “No module named tkinter“, then the Tkinter is not installed on your system.

Step 2: Install Tkinter: If Tkinter is not installed, you can install it using Homebrew. Open a command prompt window and type the following commands:

brew update 
brew install python-tk

The command above will install the Tkinter module for the default version of Python installed in your system.

Step 3: Configure the environment variables: When you have installed different versions of Python on your system and you are still encountering the error.

You should configure the path environment variables. Open a terminal window or command prompt and type the following commands:

export PYTHONHOME=/Library/Frameworks/Python.framework/Versions/3.9 
export PATH=$PYTHONHOME/bin:$PATH

Replace “3.9” with the Python version you are using. It will set the PYTHONHOME and PATH environment variables to the correct values.

Step 4: Test Tkinter: Once you have installed Tkinter and configured the environment variables, open a Python shell or the command prompt and type the following commands:

import tkinter 
root = tkinter.Tk()
root.mainloop()

This will execute a simple Tkinter window. When the window appears without any errors, then the Tkinter is working successfully on your system.

Through these following steps, you should be able to solve the “no module named _tkinter” error on MacOS and you can use Tkinter in your Python program project.

Solution 1: Install Tkinter module on Linux operating system

If you are encountering an error while trying to use the Tkinter module on your Linux system, you can follow these steps to solve it:

Step 1: Check if Tkinter is installed: Open a terminal window and type the following command:

python3 -m tkinter

The above command will execute a simple Tkinter window. When you get an error message “No module named tkinter“, so it means the Tkinter module is not installed on your computer.

Step 2: Install Tkinter: When Tkinter is not installed, you can install it using your package manager. It depends on your Linux version, the command to install Tkinter it should be different.

Debian/Ubuntu:

sudo apt-get install python3-tk

Fedora:

sudo dnf install python3-tkinter

CentOS/RHEL:

sudo yum install python3-tkinter

Arch Linux:

sudo pacman -S tk

The command above it will install the Tkinter module for Python 3 on your system.

Step 3: Test Tkinter: Once you have installed Tkinter, open a Python shell or command prompts and then type the following commands:

import tkinter
root = tkinter.Tk()
root.mainloop()

The above command will execute a simple Tkinter window. When you get an error message “No module named tkinter“, so it means the Tkinter module is not installed on your computer.

Conclusion

To conclude this article, through the following solutions above, you should be able to solve the “no module named tkinter” error on Linux, Windows, MacOS and you can use the Tkinter in your Python programs successfully.

When I try to run my program I keep getting the ImportError: No module named '_tkinter' error. I tried two things which I found could solve this problem:

sudo apt-get install python3-tk

sudo apt-get install tk-dev

They both say that they are up to date but I still get the no module named '_tkinter'.

Edit:

The error points to this line from tkinter import *

This is how I run the program that produces the error:

python3 myprog.py

asked Mar 15, 2016 at 0:04

Tom Boy's user avatar

Tom BoyTom Boy

5992 gold badges9 silver badges14 bronze badges

2

Run this code and see what it says

import sys
if sys.version_info[0] < 3:
    import Tkinter as tk     ## Python 2.x
    print("Python 2.X")
else:
    import tkinter as tk     ## Python 3.x
    print("Python 3.X")
print "version", tk.TclVersion

answered Mar 15, 2016 at 1:30

3

Bug report

I just wanted to use matplotlib to draw a line graph and save it to a file, but every time I try to import the pyplot module I get the abovementioned error message.

python3 -c "import matplotlib.pyplot"

Actual outcome

>>> import matplotlib.pyplot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/site-packages/matplotlib/pyplot.py", line 115, in <module>
    _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
  File "/usr/local/lib/python3.6/site-packages/matplotlib/backends/__init__.py", line 32, in pylab_setup
    globals(),locals(),[backend_name],0)
  File "/usr/local/lib/python3.6/site-packages/matplotlib/backends/backend_tkagg.py", line 6, in <module>
    from six.moves import tkinter as Tk
  File "/usr/local/lib/python3.6/site-packages/six.py", line 92, in __get__
    result = self._resolve()
  File "/usr/local/lib/python3.6/site-packages/six.py", line 115, in _resolve
    return _import_module(self.mod)
  File "/usr/local/lib/python3.6/site-packages/six.py", line 82, in _import_module
    __import__(name)
  File "/usr/local/lib/python3.6/tkinter/__init__.py", line 36, in <module>
    import _tkinter # If this fails your Python may not be configured for Tk
ModuleNotFoundError: No module named '_tkinter'

Expected outcome

Whatever happens when import matplotlib.pyplot succeeds

Matplotlib version

  • Operating System: Windows Subsystem for Linux
  • Matplotlib Version: 2.0.2
  • Python Version: 3.6.0

I installed matplotlib using pip.
Doing sudo apt-get install python3-tk, as recommended by someone on Stack Overflow, didn’t help.

Понравилась статья? Поделить с друзьями:
  • No module named tensorflow ошибка
  • No module named sklearn ошибка
  • Not permissible ошибка порше кайен
  • Not page fail not area ошибка виндовс
  • Not null constraint failed ошибка