From tkinter import ошибка

Всем привет! В документации написано, что tkinter имеется в стандартном наборе библиотек Python. Но при импорте модуля, интерпретатор выдаёт ошибки, что такого модуля не существует. Пробовал различные варианты:

  • import _tkinter
  • import tkinter
  • import Tkinter

Ошибка везде одинаковая:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "D:\PyCharm\PyCharm Community Edition 2019.1.3\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
ModuleNotFoundError: No module named 'tkinter

Как правильно импортировать модуль? Или его нужно установить?

Эникейщик's user avatar

Эникейщик

25.6k7 золотых знаков31 серебряный знак47 бронзовых знаков

задан 8 сен 2019 в 6:06

ChapeauClaque's user avatar

7

При установке Python на Windows нужно зайти в «Customize installation» и проверить чтобы стояла галка напротив «tcl/tk and IDLE». Если первоначально Python был установлен без этой галки, переустановка с включенной галкой должна решить эту проблему.

ответ дан 8 ноя 2019 в 17:40

insolor's user avatar

insolorinsolor

47.1k17 золотых знаков56 серебряных знаков99 бронзовых знаков

Сразу скажу, что не шарю.
Скорее всего, установил не полный пакет питона или что-то в таком духе, поэтому там просто нет tkinter (Было похожее с пайгеймом, там надо было скачать файл и установить).
Можешь проверить, есть ли он у тебя вообще в файлах.
Если нет, то тут, наверное, поможет переустановка питона.

ответ дан 8 сен 2019 в 6:32

Kenflesh's user avatar

Чтобы использовать tkinter в ОС Linux, надо установить пакет python-tk.

ответ дан 8 сен 2019 в 7:26

Anton Kulago's user avatar

Anton KulagoAnton Kulago

3682 серебряных знака13 бронзовых знаков

Тоже сначала столкнулся с этой проблемой. Справился так:

from tkinter import *

Также это может помочь:

import tkinter as tk

P.S. отвечая @insolorвведите сюда описание изображениявведите сюда описание изображения

ответ дан 17 мая 2020 в 10:44

Данил Егорин's user avatar

3

sudo pacman -S tk 

Можно попробовать для Арча, Манджаро.

ответ дан 8 июн 2020 в 11:21

KITT's user avatar

KITTKITT

33 бронзовых знака

Hello and thanks for looking at this,

When I try to import tkinter it says unresolved import

ImportError: No module named tkinter

There was some kind of error when I installed python originally

Here are the paths:

Output:

/Library/Python/2.7/site-packages
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-     scriptpackages
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip
/Users/wes/Desktop/UM/Python/guiTest
/Users/wes/Desktop/UM/Python/guiTest/testgui

Thanks
-Wes

martineau's user avatar

martineau

120k25 gold badges170 silver badges303 bronze badges

asked May 17, 2013 at 20:30

user2395350's user avatar

8

You are importing tkinter with lowercase T. The code you posted in your comment is for Python 3.X, and the import statements are correct if you have that version too, but since you are using Python 2.7, the names for the modules are Tkinter and tkMessageBox (instead of tkinter and tkinter.messagebox).

answered May 17, 2013 at 23:41

A. Rodas's user avatar

A. RodasA. Rodas

20.2k8 gold badges62 silver badges72 bronze badges

4

Finally figured it out! Thanks. My mac comes with python 2.7 in system/Library and auto config defalts to this however this is not the version that I downloaded and updated.The version that I downloaded went into Library not System and the Capital T in Tkinter was important as you said for 2.7 Thanks for your help

answered May 24, 2013 at 15:14

user2418076's user avatar

а напрямую в консоли свой код просто пробовали запускать ?

$ python --version && pacman -Q tk && echo && cat -n test1.py && echo && python test1.py
Python 3.10.4
tk 8.6.12-1

     1	from tkinter import *
     2	import tkinter as tk
     3	window = tk()
     4	window.title("Hello, Wrld!")
     5	window.mainloop()

Traceback (most recent call last):
  File "/tmp/test1.py", line 3, in <module>
    window = tk()
TypeError: 'module' object is not callable

здесь для наглядности вывел версию python и tk, а также сам текст программы и выданную ошибку (система Archlinux).

а вот пример с кодом что ниже привел AVKor
626800ec9fd7f663289087.png
всё сработало отлично

еще как вариант приведу официальный пример с tkinter — Python interface to Tcl/Tk
626805bf19121444489645.png
где так же все хорошо
все три примера аналогично ведут себя и в VScode

When I try to install tkinter using this command:

sudo apt-get install python-tk

I get this message meaning it is already installed:

Reading package lists... Done
Building dependency tree       
Reading state information... Done
python-tk is already the newest version.
The following package was automatically installed and is no longer required:
  libjpeg62
Use 'apt-get autoremove' to remove it.
0 upgraded, 0 newly installed, 0 to remove and 9 not upgraded.

When I want to import it, I get this message error:

begueradj@begueradj-darwin:~/begueradj# python
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] 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>
ImportError: No module named tkinter
>>> 

How to fix this ?

“1995 is calling… it wants its user interfaces back!”

Sorry, I couldn’t let this go. 😂 TKinter is actually a great Python library and you can use it to make modern user interfaces too. This tutorial shows you how to fix the No Module Named 'tkinter' error.

Quick Fix: 👇

Python raises the ImportError: No module named 'tkinter' when it cannot find the library tkinter. Tkinter is part of Python’s standard library, so for modern Python installations, you can just import tkinter without needing to install it first. But in some environments, you may need to install it using pip install python3-tkinter or variants thereof.

Alternatively, you may have different Python versions on your computer, and tkinter is not installed for the particular version you’re using.

Here are some variants you may want to try to fix the error and install tkinter in your environment:

💡 If you have only one version of Python installed:
pip install python3-tkinter

💡 If you have Python 3 (and, possibly, other versions) installed:
pip3 install python3-tkinter

💡 If you don't have PIP or it doesn't work
python -m pip install python3-tkinter
python3 -m pip install python3-tkinter

💡 If you have Linux and you need to fix permissions (any one):
sudo pip3 install python3-tkinter
pip3 install python3-tkinter --user

💡 If you have Linux or Ubuntu with apt
sudo apt-get install python3-tk

💡 If you're using macOS and you want to install Python 3.9 Tkinter (any):
brew install python-tk@3.9
brew install python-tk

💡 If you have Fedora
sudo dnf install python3-tkinter

💡 If you have Windows and you have set up the py alias
py -m pip install python3-tkinter

💡 If you have Anaconda
conda install -c anaconda python3-tkinter

💡 If you have Jupyter Notebook
!pip install python3-tkinter
!pip3 install python3-tkinter

💬 Summary: You see that most solutions concern a combination of the installation tool (e.g., pip or brew or conda) and any of the library name variations python3-tkinter, python-tkinter, python3-tk, or python-tk.

But as I mentioned before, likely, you don’t need to install it because it’s already part of Python’s standard library, so a simple import statement should be sufficient if your Python is correctly installed!

🌍 Recommended Tutorial: How to Install Python?

Speaking of the import statement—older versions of Tkinter came with some confusion about the capitalization of its name.

In Python 3, the module was renamed from Tkinter (Python 2) to tkinter (Python 3), as stated in the docs:

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

The following code snippet was proposed to overcome these issues for different Python versions (2 vs 3):

Instead of:

import tkinter

You can run:

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

To import Tkinter independently of your concrete (local) Python version.

By the way, this is how the error may look when you try to import the tkinter library into your (virtual) environment and Python raises the following ImportError: No module named tkinter:

>>> import tkinter
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    import tkinter
ModuleNotFoundError: No module named 'tkinter'

Windows Solution Idea: Fix the Path

The error might persist even after you have installed the tkinter library. This likely happens because pip is installed but doesn’t reside in the path you can use. Although pip may be installed on your system the script is unable to locate it. Therefore, it is unable to install the library using pip in the correct path.

To fix the problem with the path in Windows follow the steps given next.

Step 1: Open the folder where you installed Python by opening the command prompt and typing where python

Step 2: Once you have opened the Python folder, browse and open the Scripts folder and copy its location. Also verify that the folder contains the pip file.

Step 3: Now open the Scripts directory in the command prompt using the cd command and the location that you copied previously.

Step 4: Now install the library using pip install tkinter command. Here’s an analogous example:

After having followed the above steps, execute our script once again. And you should get the desired output.

Other Solution Ideas

  • The ModuleNotFoundError may appear due to relative imports. You can learn everything about relative imports and how to create your own module in this article.
  • You may have mixed up Python and pip versions on your machine. Use Python 3 and you should be able to import Tkinter without error.
  • You can also check out this article to learn more about possible problems that may lead to an error when importing a library.

Understanding the “import” Statement

import tkinter

In Python, the import statement serves two main purposes:

  • Search the module by its name, load it, and initialize it.
  • Define a name in the local namespace within the scope of the import statement. This local name is then used to reference the accessed module throughout the code.

What’s the Difference Between ImportError and ModuleNotFoundError?

What’s the difference between ImportError and ModuleNotFoundError?

Python defines an error hierarchy, so some error classes inherit from other error classes. In our case, the ModuleNotFoundError is a subclass of the ImportError class.

You can see this in this screenshot from the docs:

You can also check this relationship using the issubclass() built-in function:

>>> issubclass(ModuleNotFoundError, ImportError)
True

Specifically, Python raises the ModuleNotFoundError if the module (e.g., tkinter) cannot be found. If it can be found, there may be a problem loading the module or some specific files within the module. In those cases, Python would raise an ImportError.

If an import statement cannot import a module, it raises an ImportError. This may occur because of a faulty installation or an invalid path. In Python 3.6 or newer, this will usually raise a ModuleNotFoundError.

Related Videos

The following video shows you how to resolve the ImportError:

How to Fix : “ImportError: Cannot import name X” in Python?

The following video shows you how to import a function from another folder—doing it the wrong way often results in the ModuleNotFoundError:

How to Call a Function from Another File in Python?

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

Понравилась статья? Поделить с друзьями:
  • From sympy import ошибка
  • From pyqt5 import uic ошибка
  • From pil import image imagetk ошибка
  • From keyword not found where expected oracle ошибка
  • From keras models import sequential ошибка