Today I wanted to start working with Tkinter, but I have some problems.
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
So how can I configure my Python 3.2 to work with Tkinter?
asked Mar 28, 2011 at 13:10
Maciej ZiarkoMaciej Ziarko
11.1k13 gold badges48 silver badges69 bronze badges
3
Under Arch/Manjaro just install the package tk
:
sudo pacman -S tk
answered Apr 27, 2016 at 21:27
3
Solution for Linux, Windows (WSL/Ubuntu) and MacOS
After trying a bunch of things, this is how it finally worked:
$ brew install python-tk
rainabba
3,61134 silver badges34 bronze badges
answered May 10, 2021 at 6:27
subtleseekersubtleseeker
3,8373 gold badges25 silver badges38 bronze badges
5
Install tk-devel
(or a similarly-named package) before building Python.
answered Mar 28, 2011 at 13:14
4
To get this to work with pyenv
on Ubuntu 16.04 and 18.04, I had to:
$ sudo apt-get install python-tk python3-tk tk-dev
Then install the version of Python I wanted:
$ pyenv install 3.6.2
Then I could import tkinter just fine:
import tkinter
answered Aug 10, 2017 at 19:42
PaulMestPaulMest
11.6k6 gold badges51 silver badges49 bronze badges
3
According to 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.
answered Mar 28, 2011 at 13:15
Sandro MundaSandro Munda
39.3k24 gold badges98 silver badges121 bronze badges
5
So appearantly many seems to have had this issue (me including) and I found the fault to be that Tkinter wasn’t installed on my system when python was compiled.
This post describes how to solve the problem by:
- Removing the virtual environment/python distribution
- install Tkinter with
sudo apt-get install tk-dev
(for deb) orsudo pacman -S tk
(for arch/manjaro) - Then proceed to compile python again.
This worked wonders for me.
answered Mar 10, 2020 at 6:23
2
Had the same issue on Fedora with Python 2.7. Turns out some extra packages are required:
sudo dnf install tk-devel tkinter
After installing the packages, this hello-world example seems to be working fine on 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
And through X11 forwarding, it looks like this:
Note that in Python 3, the module name is lowercase, and other packages are probably required…
from tkinter import *
answered Jan 12, 2016 at 15:39
Stefan SaruStefan Saru
1,6832 gold badges10 silver badges4 bronze badges
1
I also faced similar problem. I resolved it by installing python-tk
in my system.
Command for mac : brew install python-tk
.
answered May 10, 2021 at 15:51
Vikas GuptaVikas Gupta
10.5k4 gold badges33 silver badges42 bronze badges
Oh I just have followed the solution Ignacio Vazquez-Abrams has suggest which is install tk-dev before building the python.
(Building the Python-3.6.1 from source on Ubuntu 16.04.)
There was pre-compiled objects and binaries I have had build yesterday though, I didn’t clean up the objects and just build again on the same build path. And it works beautifully.
sudo apt install tk-dev
(On the python build path)
(No need to conduct 'make clean')
./configure
make
sudo make install
That’s it!
answered Jun 22, 2017 at 0:42
David JungDavid Jung
3465 silver badges8 bronze badges
sudo apt-get install python3-tk
answered Jul 23, 2017 at 9:32
RafalRafal
5455 silver badges10 bronze badges
1
I encountered this issue on python 2.7.9.
To fix it, I installed tk and tcl, and then rebuild python code and reinstall, and during configure, I set the path for tk and tcl explicitly, by:
./configure --with-tcltk-includes="-I/usr/include" --with-tcltk-libs="-L/usr/lib64 -ltcl8.5 -L/usr/lib64 -ltk8.5"
Also, a whole article for python install process: Building Python from Source
answered Sep 8, 2017 at 14:00
dasonsdasons
4634 silver badges12 bronze badges
Installing Tkinter
python -m pip install tk-tools
or
sudo apt install python3-tk
Code
from tkinter import *
root = Tk()
root.title('My App')
# Code
root.mainloop()
answered Sep 26, 2021 at 11:42
now i figured out what’s going on ubuntu,
Follow these step to solve the issue
- check your python version
python3 --version
- Lets Imagine you have python 3.10
- Then Install Python-tk for the python version by using bellow command
sudo apt install python3.10-tk
simple if you have python3.8 then sudo apt install python{"use your python version here"}-tk
answered Dec 14, 2021 at 1:03
since I can not comment yet, here’s my answer to another post:
since I’m still using python 3.9, this code works for me:
brew install python-tk@3.9
if using brew install python-tk
brew will install python-tk@3.10 which is key-only
answered Sep 11, 2022 at 10:24
AnnAnn
431 silver badge4 bronze badges
1
I think the most complete answer to this is the accepted answer found here:
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/issue8555I 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.
answered Sep 9, 2016 at 20:12
mjpmjp
1,5722 gold badges22 silver badges37 bronze badges
To anyone using Windows and Windows Subsystem for Linux, make sure that when you run the python command from the command line, it’s not accidentally running the python installation from WSL! This gave me quite a headache just now. A quick check you can do for this is just
which <python command you're using>
If that prints something like /usr/bin/python2
even though you’re in powershell, that’s probably what’s going on.
answered May 22, 2018 at 5:47
If you’re running on an AWS instance that is running Amazon Linux OS, the magic command to fix this for me was
sudo yum install tkinter
If you want to determine your Linux build, try cat /etc/*release
answered Nov 14, 2018 at 4:52
StackGStackG
2,6705 gold badges26 silver badges45 bronze badges
1
This symptom can also occur when a later version of python (2.7.13, for example) has been installed in /usr/local/bin «alongside of» the release python version, and then a subsequent operating system upgrade (say, Ubuntu 12.04 —> Ubuntu 14.04) fails to remove the updated python there.
To fix that imcompatibility, one must
a) remove the updated version of python in /usr/local/bin;
b) uninstall python-idle2.7; and
c) reinstall python-idle2.7.
answered Jun 13, 2017 at 0:50
Even after installing python-tk, python3-tk I was getting error your python is not configured for Tk.
So I additionally installed tk8.6-dev
Then I build my Python again, run following again:
make,
make install.
When I did this I saw messages on screen that it is building _tkinter and related modules. Once that is done, I tried ‘import tkinter» and it worked.
answered Sep 25, 2020 at 12:47
If you are using Manjaro(Arch Linux) run below command in your terminal
sudo pacman -S tk
answered Oct 12, 2022 at 8:01
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.
13 ответов
Согласно http://wiki.python.org/moin/TkInter:
Если он не работает с «Нет модуля с именем _tkinter», ваша конфигурация Python должна быть изменена для включения этого модуля (который является модулем расширения, реализованным на C). не редактировать модули/настройки (устаревшие). Возможно, вам придется установить Tcl и Tk (при использовании RPM, также установить RPM -devel) и/или отредактировать setup.py script, чтобы указать на нужные места, где установлен Tcl/Tk. Если вы устанавливаете Tcl/Tk в местоположения по умолчанию, просто перезапуск «make» должен построить расширение _tkinter.
Sandro Munda
28 март 2011, в 13:40
Поделиться
В Arch/Manjaro просто установите пакет tk
:
sudo pacman -S tk
Jabba
27 апр. 2016, в 22:35
Поделиться
Установите tk-devel
(или пакет с похожим именем) перед созданием Python.
Ignacio Vazquez-Abrams
28 март 2011, в 13:57
Поделиться
Чтобы работать с pyenv
на Ubuntu 16.04, мне пришлось:
$ sudo apt-get install python-tk python3-tk tk-dev
Затем установите версию Python, которую я хотел:
$ pyenv install 3.6.2
Тогда я мог бы импортировать tkinter просто отлично:
import tkinter
PaulMest
10 авг. 2017, в 21:20
Поделиться
Имел ту же проблему с Fedora с Python 2.7. Оказывается, требуются дополнительные пакеты:
sudo dnf install tk-devel tkinter
После установки пакетов этот привет-мир, похоже, отлично работает на 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
И через пересылку X11 это выглядит так:
Обратите внимание, что в Python 3 имя модуля имеет строчные значения, и, возможно, необходимы другие пакеты…
from tkinter import *
Stefan Saru
12 янв. 2016, в 16:02
Поделиться
Я столкнулся с этой проблемой на Python 2.7.9.
Чтобы это исправить, я установил tk и tcl, а затем перестроил код на python и переустановил, а во время настройки я явно установил путь для tk и tcl:
./configure --with-tcltk-includes="-I/usr/include" --with-tcltk-libs="-L/usr/lib64 -ltcl8.5 -L/usr/lib64 -ltk8.5"
Также, целая статья о процессе установки Python: Сборка Python из Source
dasons
08 сен. 2017, в 14:27
Поделиться
Любой, кто использует Windows и Windows Subsystem для Linux, должен убедиться, что при запуске команды python из командной строки он не случайно запускает установку python из WSL! Это дало мне головную боль только сейчас. Быстрая проверка, которую вы можете сделать, это просто which <python command you're using>
Если это напечатает что-то вроде /usr/bin/python2
даже если вы в PowerShell, это, вероятно, то, что происходит.
bbukaty
22 май 2018, в 06:23
Поделиться
sudo apt-get install python3-tk
Rafal
23 июль 2017, в 10:36
Поделиться
О, я только что последовал за решением, которое Игнасио Васкес-Абрамс предлагает, чтобы установить tk-dev перед созданием python.
(Построение Python-3.6.1 из источника на Ubuntu 16.04.)
Были предварительно скомпилированные объекты и двоичные файлы, которые у меня были вчера, но я не очищал объекты и просто строил их снова на одном пути сборки. И это прекрасно работает.
sudo apt install tk-dev
(On the python build path)
(No need to conduct 'make clean')
./configure
make
sudo make install
Что это!
David Jung
22 июнь 2017, в 01:52
Поделиться
Вам нужно установить tkinter для python3.
В Fedora pip3 install tkinter --user
возвращает Could not find a version that satisfies the requirement
… поэтому я должен dnf install python3-tkinter
команду: dnf install python3-tkinter
. Это решило мою проблему
And0k
06 фев. 2019, в 21:49
Поделиться
Если вы работаете с экземпляром AWS под управлением ОС Amazon Linux, волшебная команда, которая исправила это для меня, была
sudo yum install tkinter
Если вы хотите определить вашу сборку Linux, попробуйте cat/etc/*release
StackG
14 нояб. 2018, в 06:15
Поделиться
Этот симптом также может возникать, когда более поздняя версия python (например, 2.7.13) была установлена в/usr/local/bin «наряду с» версией релиза python «, а затем последующим обновлением операционной системы (скажем, Ubuntu 12.04 → Ubuntu 14.04) не удаляет обновленный питон там.
Чтобы исправить эту несовместимость, нужно
a) удалите обновленную версию python в /usr/local/bin;
b) удалить python-idle2.7; и
c) переустановите python-idle2.7.
s.w.s.
13 июнь 2017, в 01:07
Поделиться
Я думаю, что наиболее полным ответом на этот вопрос является принятый ответ, найденный здесь:
Как заставить tkinter работать с Ubuntu по умолчанию Python 2.7 установить?
Я понял это после слишком много времени, потраченного на эту проблему, поэтому надеюсь, я смогу спасти кого-то еще от хлопот.
Я обнаружил, что этот старый отчет об ошибке был признан недействительным, проблема у меня была, у меня был Tkinter.py, но он не смог найти модуль _tkinter: http://bugs.python.org/issue8555
Я установил пакет tk-dev с apt-get и перестроил Python, используя .configure, make и make install в каталоге Python2.7.3. А также теперь мой Python2.7 может импортировать Tkinter, yay!
Я немного удивлен, что пакет tk-dev вообще не упоминается в документация по установке Python…. ниже — еще одна полезная ресурс по отсутствующим модулям на Python, если, как и я, кто-то должен обнаружите, что они пропали больше, чем _tkinter.
mjp
09 сен. 2016, в 20:49
Поделиться
Ещё вопросы
- 0Следующая программа выдает ошибку доступа к памяти
- 0Повторите порядок по данным php json_encode
- 0Необходимо найти общую сумму (сумму) с 5 вечера в один день до 5 утра на следующий день в MySQL
- 0google api calendar php
- 0автоматический выбор ч: флажок в JSF DataTable
- 0Я звоню на многие сессии JQuery?
- 0Не удается получить дату из поля ввода и превратить ее в объект даты в IE8
- 0Навигация в Html5Mode включена и выключена
- 0SQL — Выберите Топ результат для каждого игрока в последних 10 результатах каждого игрока
- 0Отображение определенных сообщений об ошибках через Errno 1062
- 1Что представляет собой параметр Paint.setTextSize ()?
- 1Regex получает другие слова
- 1Как узнать пользовательский агент браузера в Android
- 1Преобразование списка <string> в IEnumerator <string>
- 0Как добавить текущее время в формате datetime в текстовое поле в yii?
- 1Android-виджет с изменяющимся текстом
- 1Проблема с разницей в поведении при нагрузке между Chrome 56 и Chrome 60
- 0Node.js + Espress + MySQL как хранилище документов (результаты)
- 0Вставка выпадающего элемента между двумя элементами списка с использованием JavaScript
- 0Проблемы с анализом ввода
- 1Проблема Android MediaPlayer
- 1Как создать виртуальную машину ADT определенного размера, в которой все еще есть кнопки управления оборудованием?
- 0Ошибка сегментации C ++ — std :: map.insert ()
- 1Самостоятельная ошибка при запуске локальной команды с fabric2
- 1Создание объекта подкласса аккаунта
- 1InterfaceError (0, ») при отправке параллельных запросов
- 0Условное отображение элементов формы
- 0Звонить по ссылке в CSS?
- 1Как моя функция может принимать CSV-файлы в качестве входных данных?
- 1Подавить вывод в matplotlib
- 0Как установить значение оси X HighCharts
- 0Videogular — это vg-control не работают с плагином vg-quality
- 0PHP / MySQL n-ая строка с DATE_SUB и т. Д.
- 1Как получить результат / обратная связь / количество строк / количество строк, затронутых запросом MERGE во фрагменте Python
- 1VisualStyleRenderer возвращает ошибку для пункта меню
- 0Один тест Угловой контроллер Карма-Жасмин работает, но не другой
- 0Ссылка на две таблицы в базе данных SQL
- 0Пытаюсь выучить винапы. сделал первую программу, которая должна показать мне окно. CMD показывает но нет окна
- 0утечка памяти в контейнере с ++
- 0JavaScript — очистка элемента
- 1Почему событие отметки времени в новом классе вызывает метод из form1 один раз, а в следующий раз он ничего не делает?
- 0Динамическая загрузка меню в jsp
- 1Попытка проверить соединение на локальных портах с помощью Socket и получить ConnectException
- 1javascript привязать обратный вызов к любой функции
- 0PHP генерирует категорию и подкатегорию из базы данных [дубликаты]
- 0Используйте Javascript, чтобы сделать кнопки HTML
- 1Python Pandas — Как подавить PerformanceWarning?
- 0Многоязычность в Codeigniter
- 0Сбой jQuery Rotater, когда я скрываю и показываю новый контент
- 0Ошибка создания одного класса в форме C ++
Question :
Tkinter: “Python may not be configured for Tk”
Today I wanted to start working with Tkinter, but I have some problems.
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
So how can I configure my Python 3.2 to work with Tkinter?
Answer #1:
According to 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.
Answer #2:
Under Arch/Manjaro just install the package tk
:
sudo pacman -S tk
Answer #3:
Install tk-devel
(or a similarly-named package) before building Python.
Answer #4:
To get this to work with pyenv
on Ubuntu 16.04 and 18.04, I had to:
$ sudo apt-get install python-tk python3-tk tk-dev
Then install the version of Python I wanted:
$ pyenv install 3.6.2
Then I could import tkinter just fine:
import tkinter
Answer #5:
Had the same issue on Fedora with Python 2.7. Turns out some extra packages are required:
sudo dnf install tk-devel tkinter
After installing the packages, this hello-world example seems to be working fine on 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
And through X11 forwarding, it looks like this:
Note that in Python 3, the module name is lowercase, and other packages are probably required…
from tkinter import *
Answer #6:
Oh I just have followed the solution Ignacio Vazquez-Abrams has suggest which is install tk-dev before building the python.
(Building the Python-3.6.1 from source on Ubuntu 16.04.)
There was pre-compiled objects and binaries I have had build yesterday though, I didn’t clean up the objects and just build again on the same build path. And it works beautifully.
sudo apt install tk-dev
(On the python build path)
(No need to conduct 'make clean')
./configure
make
sudo make install
That’s it!
Answer #7:
I encountered this issue on python 2.7.9.
To fix it, I installed tk and tcl, and then rebuild python code and reinstall, and during configure, I set the path for tk and tcl explicitly, by:
./configure --with-tcltk-includes="-I/usr/include" --with-tcltk-libs="-L/usr/lib64 -ltcl8.5 -L/usr/lib64 -ltk8.5"
Also, a whole article for python install process: Building Python from Source
Answer #8:
So appearantly many seems to have had this issue (me including) and I found the fault to be that Tkinter wasn’t installed on my system when python was compiled.
This post describes how to solve the problem by:
- Removing the virtual environment/python distribution
- install Tkinter with
sudo apt-get install tk-dev
(for deb) orsudo pacman -S tk
(for arch/manjaro) - Then proceed to compile python again.
This worked wonders for me.
Thread Rating:
- 0 Vote(s) — 0 Average
- 1
- 2
- 3
- 4
- 5
IDLE can’t import Tkinter |
I’m using red hat and uninstalled a prior 2.7.5 python version to install the 3.6.8 version with the idle, tk and tkinter however, no matter how I install the products I got the following message when I try to start idle3: ** IDLE can’t import Tkinter. Could someone please point me in the right direction? Thanks! Posts: 166 Threads: 7 Joined: Nov 2018 Reputation:
try this link here build tlc Posts: 521 Threads: 0 Joined: Feb 2018 Reputation: For Python3.X use a lower case t import tkinter Posts: 4 Threads: 2 Joined: May 2019 Reputation: The issue was solved after installing Python manually (configure, make, install…) instead of the software manager. Thanks! |
Possibly Related Threads… | |||||
Thread | Author | Replies | Views | Last Post | |
|
[Tkinter] Tkinter Class Import Module Issue | AaronCatolico1 | 6 | 611 |
Sep-06-2022, 03:37 PM Last Post: AaronCatolico1 |
[Tkinter] Tkinter — I have problem after import varaible or function from aGUI to script | johnjh | 2 | 1,930 |
Apr-17-2020, 08:12 PM Last Post: johnjh |
|
import Tkinter | orestgogosha | 1 | 2,194 |
Mar-27-2020, 03:32 PM Last Post: DT2000 |
|
[Tkinter] Top Level Window — from tkinter import * | francisco_neves2020 | 6 | 3,129 |
Apr-23-2019, 09:27 PM Last Post: francisco_neves2020 |
|
tkinter import problems on mac | Lux | 2 | 5,547 |
Jul-30-2017, 07:14 PM Last Post: Larz60+ |