- Проблема с подключением модуля tkinter в PyCharm Python
- 3 ответа 3
- Modulenotfounderror no module named tkinter linux
- # ModuleNotFoundError: No module named ‘tkinter’ in Python
- # Installing the tkinter module
- # Tick the tcl/tk and IDLE option on Windows
- # Tkinter is a built-in module in Python 3
- # An import statement that works in both Python 3 and Python 2
- # Using the tkinter module in a virtual environment
- # Make sure you haven’t named your file tkinter.py
- # NameError: name ‘tk’ is not defined in Python
- RHEL/Pyenv: No module named ‘_tkinter’
Проблема с подключением модуля tkinter в PyCharm Python
Пытаюсь запустить через PyCharm тестовую программу с использованмем tkinter со стороками:
try: import Tkinter as tk # this is for python2 except: import tkinter as tk # this is for python3 Ответ:ModuleNotFoundError: No module named 'tkinter'
sudo apt-get install python3-tk прошло нормально
python -m tkinter окошко показывает, работает нормально
Тестовая программка на PySimpleGUI (требует tkinter) при запуске в системной консоли работает.
В настройках PyCharm->Progect Interpreter-> + модуля tkinter нет есть масса дополнительных к tkinter модулей В настройках PyCharm->Progect Interpreter-> pip модуля tkinter нет
Попытка поставить модуль через PIP не проходит
pip3 install tkinter ERROR: Could not find a version that satisfies the requirement tkinter (from versions: none) ERROR: No matching distribution found for tkinter
Вопрос: как подключить в PyCharm модуль tkinter с учетом того, что типовые методы не сработали.
«как подключить в PyCharm» — а причём тут PyCharm ?! Если Вы подозреваете, что при запуске скрипта в IDE PyCharm что-то не так настраивается, то запустите скрипт из командной строки: python3 programm.py и сразу станет ясно, при делах здесь PyCharm, или нет.
3 ответа 3
Я столкнулся с точно такой же проблемой, и я обнаружил, что это проблема самого PyCharm. При запуске в терминале интерпретатора python из виртуального окружения все импорты нормально работают, но вот при запуске программы из самого PyCharm с тем же виртуальным окружением появляется ошибка. Причем, если внимательно посмотреть на сообщение об ошибке, мы увидим, что импорт происходит через некий пакет pydev_bundle внутри PyCharm, который и генерирует эту ошибку. Разобраться более детально, как этот пакет устроен, и действительно ли проблема именно в нем, я не смог.
Но вспомнив, что я установил PyCharm через Flatpak, я подумал, что проблема может быть именно в этом. Удалил PyCharm и установил заново, скачав дистрибутив с сайта разработчика. Все стало работать как надо. Я уже сталкивался с аналогичной проблемой, когда установил Sublime через тот же Flatpak — он тоже «не видел» некоторых модулей системного python. Проблема аналогично решилась, когда я установил sublime из репозитория разработчика. Почему это так — не знаю, надо разбираться с самим Flatpak, очевидно, проблема в нем.
UPD: Как я и думал, проблема в том, что Flatpak «упаковывает» приложения в изолированное окружение, из которого им недоступны пакеты, установленные в системе. Так что PyCharm ни в чем не виноват, а вот о наличии такой проблемы стоило бы предупреждать всех, кто будет устанавливать IDE (эту или любую другую) через Flatpak.
Modulenotfounderror no module named tkinter linux
Last updated: Apr 18, 2022
Reading time · 4 min
# ModuleNotFoundError: No module named ‘tkinter’ in Python
The Python «ModuleNotFoundError: No module named ‘tkinter'» occurs when tkinter is not installed in our Python environment.
To solve the error, install the module and import it as import tkinter as tk .
# Installing the tkinter module
Open your terminal and run the following command to install tkinter.
Copied!# 👇️ === UBUNTU / DEBIAN === sudo apt-get install python3-tk # 🚨 Make sure to specify correct Python version. # For example, my Python v is 3.10, so I would install as sudo apt-get install python3.10-tk # 👇️ === MacOS === brew install python-tk@3.10 # 🚨 Make sure to specify correct Python version. # For example, if you run Python v3.9 run adjust command to brew install python-tk@3.9 # 👇️ === Fedora === sudo dnf install python3-tkinter # 👇️ === CentOS === sudo yum install python3-tkinter
You can check your Python version with the python —version command.
Copied!python --version python3 --version
# Tick the tcl/tk and IDLE option on Windows
If you are on Windows , you have to make sure to tick the checkbox tcl/tk and IDLE when installing Python.
If you already installed Python, download the installer, run it and click Modify .
Then check the tcl/tk and IDLE checkbox to install tkinter for your Python version.
Make sure to tick the following options if 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)
# Tkinter is a built-in module in Python 3
Tkinter comes as a built-in module in Python 3 and is made available without requiring installation.
Now you should be able to import and use the tkinter module.
Copied!import tkinter as tk from tkinter import ttk root = tk.Tk() frm = ttk.Frame(root, padding=10) frm.grid() ttk.Label(frm, text="Hello World!").grid(column=0, row=0) ttk.Button(frm, text="Quit", command=root.destroy).grid(column=1, row=0) root.mainloop()
Note that in Python 3, tkinter is imported using a lowercase t , whereas in Python 2, it is imported with an uppercase T
When you run your code with python file_name.py , you might be running the script with Python 2.
Use the python —version command if you need to check your Python version.
You can try to run the script with python3 file_name.py to have the command scoped to Python 3.
If you get the error «AttributeError: module ‘tkinter’ has no attribute ‘Tk'», click on the following article.
# An import statement that works in both Python 3 and Python 2
If your code can be run using both Python 3 and 2, use a try/except statement for a universal import.
Copied!try: import tkinter as tk # using Python 3 from tkinter import ttk except ImportError: import Tkinter as tk # falls back to import from Python 2
We try to import the tkinter module (Python 3) and if we get an ImportError , we know the file is run in Python 2, so we import using an uppercase T and alias the import to tk .
If you aren’t sure what version of Python you’re using, run the python —version command.
# Using the tkinter module in a virtual environment
If you are in a virtual environment, the version of Python corresponds to the version that was used to create the virtual environment.
Here is an example of creating a virtual environment using Python 3 where tkinter is available without installation required.
Copied!# 👇️ use correct version of Python when creating VENV python3 -m venv venv # 👇️ activate on Unix or MacOS source venv/bin/activate # 👇️ activate on Windows (cmd.exe) venv\Scripts\activate.bat # 👇️ activate on Windows (PowerShell) venv\Scripts\Activate.ps1
If the python3 -m venv venv command doesn’t work, try the following 2 commands:
Make sure to use the correct activation command depending on your operating system.
Once you activate the virtual environment, try running your script directly with python script_name.py .
# Make sure you haven’t named your file tkinter.py
If the error persists, make sure you haven’t named a module in your project as tkinter.py because that would shadow the original tkinter module.
You also shouldn’t be declaring a variable named tkinter as that would also shadow the original module.
# NameError: name ‘tk’ is not defined in Python
If you get an error such as «NameError: name ‘tk’ is not defined», then you have forgotten to import tkinter before using it.
Copied!root = tk.Tk() NameError: name 'tk' is not defined. Did you mean 'ttk'?
We have to import the tkinter module to solve the error.
Copied!# ✅ import tkinter as tk first import tkinter as tk from tkinter import ttk root = tk.Tk() frm = ttk.Frame(root, padding=10) frm.grid() ttk.Label(frm, text="Hello World!").grid(column=0, row=0) ttk.Button(frm, text="Quit", command=root.destroy).grid(column=1, row=0) root.mainloop()
Even though the tkinter module is in the Python standard library, we still have to import it before using it.
An alternative to importing the entire tkinter module is to import only the classes and methods that your code uses.
Copied!# ✅ importing tkinter first from tkinter import Tk, ttk root = Tk() frm = ttk.Frame(root, padding=10) frm.grid() ttk.Label(frm, text="Hello World!").grid(column=0, row=0) ttk.Button(frm, text="Quit", command=root.destroy).grid(column=1, row=0) root.mainloop()
The example shows how to only import the Tk class and ttk module from tkinter .
Instead of accessing the members on the module, e.g. tk.Tk() , we now access them directly.
This should be your preferred approach because it makes your code easier to read.
For example, when we use an import such as import tkinter as tk , it is much harder to see which functions or classes from the tkinter module are being used in the file.
Conversely, when we import specific functions, it is much easier to see which classes from the tkinter module are being used.
You can view all of the classes and modules tkinter provides by visiting the official docs.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
RHEL/Pyenv: No module named ‘_tkinter’
However the suggested solution is usually to install tkinter using a package manager. However I’ve tried installing:
2872 sudo yum install rh-python36-python-tkinter 2873 sudo yum install rh-python35-python-tkinter 2874 sudo yum install rh-python34-python-tkinter 2891 sudo yum install tkinter 2893 sudo yum install python36-tkinter 2902 sudo yum install gcc zlib-devel bzip2 bzip2-devel readline-devel sqlite sqlite-devel openssl-devel tk-devel gdbm-devel ncurses-devel gl.. 2916 sudo yum install tkinter.x86_64 rh-python36-python-tkinter.x86_64 rh-python35-python-tkinter.x86_64 rh-python34-python-tkinter.x86_64 p.. 2921 sudo yum install tcl 2933 sudo yum install tk-devel 2934 sudo yum install tk 3000 sudo yum install tkinter 3026 sudo yum install tix 3031 sudo yum install tk 3032 sudo yum install tk-devel > 3033 sudo yum install tcl-devel
with each already having been installed or making no difference (having rebuilt python each time a new package was installed. The system python is able to locate tkinter:
→ /usr/bin/python3.6 Python 3.6.3 (default, Jan 4 2018, 16:40:53) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import tkinter >>>
so I’m unsure how to install python using pyenv and have it use the same version of tkinter? UPDATE: Having found that build configuration options can be set using $PYTHON_CONFIGURE_OPTS I’ve tried specifying the library locations using (for linuxbrew downloaded tcl/tk):
export PYTHON_CONFIGURE_OPTS="--with-tcltk-includes=-I/home/linuxbrew/.linuxbrew/opt/tcl-tk/include --with-tcltk-libs=-L/home/linuxbrew/.linuxbrew/opt/tcl-tk/lib" pyenv install 3.6.5
export PYTHON_CONFIGURE_OPTS="--with-tcltk-includes=-I/usr/include --with-tcltk-libs=-L/usr/lib64" pyenv install 3.6.5
→ whereis tcl tcl: /usr/lib64/tcl8.5 /usr/include/tcl.h /usr/share/tcl8.5 → whereis tcl tcl: /usr/lib64/tcl8.5 /usr/include/tcl.h /usr/share/tcl8.5