From tkinter import ошибка

Ok. First off:

What you shouldn’t do:

In production, if you are not sure whether a module is called one way or another (which might be depending on the Python version that is installed), you should not put all the imports together like that, because if one fails it will raise an import error and that will crash your runtime. Do the following:

try:
    import Tkinter

except ImportError:  # Python 3.x present
    import tkinter

However in your case you already know that you have Python 3 so that is not a problem. Just use the correct one (keep reading to the next section).

What it is recommendable that you do:

If you are using Python 2.x:

Module is named Tkinter. You can do from Tkinter import * and Tk will be imported.

If you are using Python 3.x:

Module is named tkinter. Note lowercase. You have to do import tkinter; and use tkinter.Tk

Rationale

You might want to read this fragment from this answer already posted on SO:

However, PEP8 has this to say about wildcard imports:

Wildcard imports ( from import * ) should be avoided

In spite of countless tutorials that ignore PEP8, the PEP8-compliant
way to import would be something like this:

import tkinter as tk

When importing in this way, you need to prefix all tkinter commands
with tk. (eg: root = tk.Tk(), etc). This will make your code easier to
understand at the expense of a tiny bit more typing. Given that both
tkinter and ttk are often used together and import classes with the
same name, this is a Good Thing. As the Zen of python states:
«explicit is better than implicit».

Note: The as tk part is optional, but lets you do a little less
typing: tk.Button(…) vs tkinter.Button(…)

Full answer: https://stackoverflow.com/a/11621141/4396006

Why your interpreter does not import Tk

I am uncertain on why your interpreter does not import Tk for that usage. You have to provide more details to be able to solve that part of your problem.

Edit: the line from tkinter import * includes the namespace of the __init__.py file in the tkinter module folder into your file. Therefore you should check:

  1. Where is PyCharm importing the tkinter module from. You can go to the tkinter word in your import, get the contextual menu with the right click, and go to: Go to --> Declaration (or just hit Ctrl+B). It should take you to that __init__.py file where Tk should be a class defined in there.

  2. Whether your Python Path when you run the file is fetching that folder you found the Tk module in.

If any of this is not ok, then it’s probably because your installation is broken. I’d be helpful if you told us if only from tkinter import * does not work or if import tkinter; tkinter.Tk is not defined either. You should go for a clean install.

To help us know the root of the problem, try to run the same code from the terminal or in the Python’s console and see what happens.

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

119k25 gold badges165 silver badges294 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.1k8 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

Люди: у меня похожая проблема — не устанавливается «tkinter»:

Кликните здесь для просмотра всего текста

pip install tkinter
ERROR: Could not find a version that satisfies the requirement tkinter (from versions: none)
ERROR: No matching distribution found for tkinter

Я занялся изучением «Python», и пробуя установить среду использовал следующие варианты:
«Anaconda» — «tkinter» не ставится.
«python-3.6.0» (для моей Windows 7) — в командной строке отказался устанавлявать библиотеки, «почитав» выяснил — что нужно виндовую командную строку (FarComander не прокатил)(а «Anaconda» нормально в своей строке ставила); и здесь получил ошибки на «pip install pyautogui»:

Кликните здесь для просмотра всего текста

***Running setup.py install for pyautogui … done
ERROR: pip’s dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
mouseinfo 0.1.3 requires Pillow<=3.4.2,>=2.0.0; python_version == «3.2», but you have pillow 8.3.2 which is incompatible.
mouseinfo 0.1.3 requires Pillow<=4.3.0,>=2.0.0; python_version == «3.3», but you have pillow 8.3.2 which is incompatible.
mouseinfo 0.1.3 requires Pillow<=5.4.1,>=2.5.0; python_version == «3.4», but you have pillow 8.3.2 which is incompatible.
Successfully installed Pillow***

и ту-же ошибку на «pip install tkinter».
— Может этого пакета вообще нету? Может его переименовали? Или мне пакет для игр ставить ?

Добавлено через 14 минут
Вычитал что «tkinter» уже установлен в системе (у меня семёрка) и инсталлировать его не надо — а просто подключить:

import tkinter

Анаконда

на это выдала:

Кликните здесь для просмотра всего текста

Имя «import» не распознано как имя командлета, функции, файла скрипта или выпол
няемой программы. Проверьте правильность написания имени, а также наличие и пра
вильность пути, после чего повторите попытку.
строка:1 знак:7
+ import <<<< tkinter
+ CategoryInfo : ObjectNotFound: (import:String) [], CommandNotFo
undException
+ FullyQualifiedErrorId : CommandNotFoundException

— что это значит?

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.

Понравилась статья? Поделить с друзьями:
  • Fr 3130 atego ошибка
  • From pil import image imagetk ошибка
  • Fr 3031 ошибка мерседес
  • From kivy app import app выдает ошибку
  • Fr 1125 ошибка мерседес атего