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:
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/.
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.
Пройдите тест, узнайте какой профессии подходите
Работать самостоятельно и не зависеть от других
Работать в команде и рассчитывать на помощь коллег
Организовывать и контролировать процесс работы
Быстрый ответ
Чтобы приступить к созданию графического интерфейса пользователя (GUI) на Python с применением библиотеки tkinter, выполните следующие действия:
- На Linux/macOS введение в терминале команды:
sudo apt-get install python3-tk
- Всем пользователям Windows важно знать, что tkinter уже включен в базовую поставку Python.
Если вспомнить — команды для установки даже не потребовались! Задача решена с усмешкой 😁.
- Если вы используете Virtualenv на любой операционной системе, запомните такую команду:
pip install tk
Воспользуйтесь таким тестовым примером для проверки установки:

Установка tkinter в разных дистрибутивах Linux
Установка tkinter в меру отличается, в зависимости от выбранного вами дистрибутива Linux:
-
Поклонникам Debian и пользователям Ubuntu:
-
Пользователям Fedora:
-
Адептам Arch Linux:
-
Если у вас возникла ошибка no module named _tkinter:
Визуализация
Смело представляйте процесс установки tkinter как процесс сборки конструктора LEGO® для вашего GUI-приложения на Python:
После import tkinter as tk
реализуется следующая цепочка: найден недостающий элемент (❓) ➡ он добавляется в арсенал инструментов! 🛠️
И посмотрите на получившийся результат:
Откиньтесь на спинку стула, расслабьтесь и позвольте tkinter творить чудеса GUI! 🪄🐍
Бестормозная установка tkinter: лучшие практики
Чтобы установка tkinter состоялась без проблем, следуйте этому руководству:
- Проверяйте названия пакетов – важно, чтобы вы точно знали, что вводить в командную строку.
- Используйте пакетный менеджер – забудьте о сложностях сборки из исходного кода.
- Следите за соответствием версии Python с версией пакета tkinter.
- После установки выполните тест, чтобы гарантировать работоспособность tkinter.
Использование графического пакетного менеджера Synaptic
Для тех, кто предпочитает графический интуитивно понятный интерфейс, пакетный менеджер Synaptic для систем на базе Debian предлагает удобный способ установки tkinter:
- Используйте функцию поиска для нахождения
python3-tk
. - Выберите пакет для установки.
-
Завершите процесс нажатием на кнопку Применить изменения.
Всё просто, безопасно и эффективно.
Распространенные ошибки и методы их решения
Ошибка ModuleNotFoundError
Если вы столкнулись с ошибкой ModuleNotFoundError: No module named '_tkinter'
, не паникуйте:
- Убедитесь, что версия пакета tkinter соответствует версии Python.
- Попробуйте переустановить пакет, чтобы исправить возможные неполадки.
Ошибка ImportError
Если на экране появляется сообщение ImportError: No module named tkinter
, проверьте следующее:
- Убедитесь в правильности написания
import tkinter
(только для Python 3). - Внимательно следите за настройкой виртуальных окружений, tk может потребовать установки через
pip install tk
.
Отдельная установка: когда это необходимо
Иногда бывает необходимо взяться за установку самостоятельно. Для компиляции и установки tcl/tk из исходных кодов нужно выполнить такие шаги:
- Скачать и использовать исходные коды tcl и tk.
- Следуйте инструкциям в файле README для компиляции.
-
Установите собранные модули с помощью команд:
-
Используйте ключ
--prefix
, чтобы задать путь установки.
Множественная установка Tkinter: эффективные методы
При возникновении необходимости установить tkinter на несколько систем пользуйтесь следующими приёмами:
- Автоматизируйте процесс – создавайте скрипты для упрощения задачи.
- Контейнеризация – через Docker упакуйте свою среду, облегчив таким образом развертывание tkinter.
- Используйте системы управления конфигурацией, такие как Ansible, чтобы с легкостью копировать вашу установку tkinter на другие машины.
Полезные материалы
- TkInter – Python Wiki — ваш надежный источник информации о tkinter.
- TkDocs Tutorial — пошаговый путеводитель по созданию GUI в tkinter.
- «Frequent ‘tkinter’ Questions – Stack Overflow — изучайте часто встречающиеся вопросы и набирайтесь опыта.
- Welcome to Python.org — статья Python, посвященная tkinter.
- Программирование GUI на Python с помощью Tkinter – Real Python — подробнеющее руководство с примерами.
- tkinter — Python interface to Tcl/Tk — Python 3.12.2 documentation — официальная документация Python, посвященная tkinter.
- Tkinter GUI Programming by Example | Packt — изучение tkinter через практические примеры и практическое применение.
If you’re encountering the ModuleNotFoundError: No module named ‘tkinter’ error while working with Python, don’t worry! This error typically occurs when the tkinter package isn’t installed on your system. Let’s explore how to fix this common issue.
For a broader understanding of similar Python errors, check out our guide on How To Solve ModuleNotFoundError: No module named in Python.
What is Tkinter?
Tkinter is Python’s standard GUI (Graphical User Interface) package. It’s used to create desktop applications with graphical interfaces using widgets like buttons, text boxes, and windows.
Common Causes of the Error
The error usually appears when you try to import tkinter like this:
import tkinter as tk
# or
from tkinter import *
Traceback (most recent call last):
File "your_script.py", line 1, in
import tkinter
ModuleNotFoundError: No module named 'tkinter'
How to Fix the Error
1. For Windows Users
On Windows, Tkinter usually comes with Python installation. If it’s missing:
- Uninstall your current Python installation
- Download Python from python.org
- During installation, ensure you check «tcl/tk and IDLE» option
2. For Linux Users
Install Tkinter using your distribution’s package manager:
# For Ubuntu/Debian
sudo apt-get install python3-tk
# For Fedora
sudo dnf install python3-tkinter
# For CentOS/RHEL
sudo yum install python3-tkinter
3. For macOS Users
Install Python with Homebrew:
brew install python-tk
Verifying the Installation
To check if Tkinter is properly installed, run Python in interactive mode:
import tkinter
tkinter._test()
This should open a test window if Tkinter is installed correctly.
Simple Test Program
Try this simple program to test your Tkinter installation:
import tkinter as tk
root = tk.Tk()
root.title("Tkinter Test")
label = tk.Label(root, text="Hello, Tkinter!")
label.pack()
root.mainloop()
Conclusion
The ModuleNotFoundError: No module named ‘tkinter’ is usually easy to fix by installing the appropriate package for your operating system. Remember to:
- Verify your Python installation
- Use the correct installation command for your OS
- Test the installation using the provided code examples
If you continue experiencing issues, ensure you have administrative privileges and your system’s package manager is up to date.
Operating System
Windows 10
Python version
3.x
IDE: Pycharm Community 2020 . 3
I wish I could provide more info, but the code below does not run at all, same error message.
import PySimpleGUI as sg print(sg) # Location of your PySimpleGUI.py file print(sg.version) # PySimpleGUI version number print(sg.tclversion_detailed) # tkinter detailed version number (in PySimpleGUI version 4.29.0+) print(sg.sys.version) # Python version number
There is not tkinter module available in Pycharm, there are 20 with the name in it, but no main module that seems to provide the basic tkinter.
Code To Duplicate
import PySimpleGUI as sg
triggers the error message:
ModuleNotFoundError: No module named ‘tkinter’
Last Updated :
23 May, 2024
On Ubuntu, while working with Python modules, you might encounter the «Tkinter Module Not Found» error. This typically happens because Tkinter is not installed by default with Python on some systems. Fortunately, resolving this issue involves a few simple steps to install the necessary Tkinter packages.
In this article, we will explore the reasons behind the occurrence of the “Tkinter Module Not Found On Ubuntu” error and discuss approaches to resolve it.
What is ModuleNotFoundError: No module named ‘tkinter’?
The «ModuleNotFoundError: No module named ‘tkinter‘» error occurs when Python cannot find the Tkinter module, which is necessary for creating graphical user interfaces. This error typically indicates that Tkinter is not installed on your system. To resolve this, you need to install the Tkinter package using your package manager (e.g., apt on Ubuntu).
Syntax:
ModuleNotFoundError: No module named 'tkinter'
Reason for ModuleNotFoundError: No module named ‘tkinter’
Below, are the reasons for “ModuleNotFoundError: No module named ‘tkinter’” In Python occurring.
- Module Not Installed
- Incorrect Module Name
Module Not Installed
One common reason for this error is that the tkinter module is not installed on your system. To check if this is the case, try importing the module in a Python script. If the module is not installed, the interpreter will raise the “ModuleNotFoundError.”
Python
from tkinter import *
Output:
ModuleNotFoundError: No module named 'tkinter'
Incorrect Module Name
Another reason for the error might be a typo or incorrect naming when trying to import the tkinter module. Python is case-sensitive, so ensure that the module name is spelled correctly.
Python
from TKINTER import *
Output:
ModuleNotFoundError: No module named 'TKINTER'
Approaches to Solve “Modulenotfounderror: No Module Named ‘tkinter′”
Below, are the approaches to solve “Modulenotfounderror: No Module Named ‘tkinter′” .
- Install tkinter Module
- Check Module Name
Install tkinter Module
Ensure that the tkinter module is installed on your system. You can install it using the following command:
sudo apt-get install python3-tk
Check Module Name
Double-check the spelling and case sensitivity of the module name when importing it in your script.
Python
from tkinter import * # Correct
Conclusion
The “ModuleNotFoundError: No module named ‘tkinter′” error is a common issue in Ubuntu, but it can be easily resolved by following the approaches mentioned in this article. Whether it’s installing the tkinter module, checking the correct module name, or ensuring the virtual environment is activated, these steps will help you overcome this error and continue working with tkinter module in your Python scripts.