Как установить tkinter в pycharm windows

In this tutorial we demonstrate how to install Tkinter on multiple platforms. Every platform has individual commands to install Tkinter in Python.
  1. Install Tkinter on Windows
  2. Install Tkinter on Linux
  3. Install Tkinter on Mac Operating System
  4. Install Tkinter in Pycharm

Install Tkinter

This tutorial will demonstrate how to install Tkinter on multiple platforms. Every platform has individual commands to install Tkinter in Python.

Install Tkinter on Windows

Tkinter offers multiple GUI libraries to develop GUI applications. The Tkinter is one of the popular libraries to build GUI system interfaces.

To install Tkinter, we have to install Python; if it is already installed, we can move on to install Tkinter. When we start the installation of Python, we can check td or tk and IDLE Tkinter during installation.

This way, this Tkinter will come along with Python packages, and we do not need to install it separately. However, if we lose installing Tkinter during the installation of Python, we can do it later using the pip command.

We can confirm the Python version using this command.

python --version

Pip’s version is checked using this command.

pip -V

Now we are ready to install Tkinter.

pip install tk

Now we can use the tkinter library. To confirm the tkinter library is installed, write the code in the shell.

import tkinter
tkinter._test()

If you are an Anaconda user, you can use the following command.

conda install -c anaconda tk

Install Tkinter on Linux

There are different variants of the Linux operating system. This section will learn how to install Tkinter in multiple variants.

Use this command if you’re using a Debian-based Linux operating system.

# python2 user
sudo apt-get install python-tk
# python3 user
sudo apt-get install python3-tk

Use this command if you’re using one of these: RHEL, CentOS, Oracle Linux.

sudo yum install -y tkinter tk-devel

The Fedora-based Linux operating system uses this command.

sudo pacman -S tk

Use this command to confirm the tkinter library is installed successfully.

python -m Tkinter

Install Tkinter on Mac Operating System

There are two ways to install the tkinter library in MacOS. The Mac user will follow these steps.

Run the below command to check that python3 is installed.

python3 --version

Run the below command to check that pip3 is installed.

pip3 --version

If your pip is outdated, please upgrade your pip using the below command.

pip3 install --upgrade pip

We will use pip3 as the first method. Write the following command to install Tkinter.

pip3 install tk

The second method needs a setup.py file to install the Tkinter.

We have to download the latest version of Tkinter in python3 using this command.

curl https://files.pythonhosted.org/packages/a0/81/
742b342fd642e672fbedecde725ba44db44e800dc4c936216c3c6729885a/tk-0.1.0.tar.gz > tk.tar.gz

Write the following command to extract the downloaded package.

tar -xzvf tk.tar.gz

Go to the extracted folder and run this command.

python3 setup.py install

To ensure the tkinter library is installed, run this code in the Python terminal.

import tk

Install Tkinter in Pycharm

The installation process is very simple in Pycharm IDLE. Pycharm IDLE is more convenient for users.

There is an interface to install the tkinter library without running a command.

Go to File>Settings>Project>Python Interpreter and click the + button, search tk, and click the Install Package button. You can select the specific version.

Install Tkinter in Pycharm

Click here to read more about Tkinter.

I used sudo apt-get install python3.6-tk and it works fine. Tkinter works if I open python in terminal, but I cannot get it installed on my Pycharm project. pip install command says it cannot find Tkinter. I cannot find python-tk in the list of possible installs either.

Is there a way to get Tkinter just standard into every virtualenv when I make a new project in Pycharm?

Edit: on Linux Mint

Edit2: It is a clear problem of Pycharm not getting tkinter guys. If I run my local python file from terminal it works fine. Just that for some reason Pycharm cannot find anything tkinter related.

asked Dec 15, 2018 at 21:55

TheProgramMAN123's user avatar

8

Make sure you use the right import statement for your version of Python.

Python 2.7

from Tkinter import *

For Python 3.x

from tkinter import *

answered Jul 3, 2019 at 18:17

Mattatat-tat's user avatar

Mattatat-tatMattatat-tat

4491 gold badge7 silver badges9 bronze badges

For python 2 use:

sudo apt-get install python-tk

For python 3 use:

sudo apt-get install python3-tk

When you display info about packages it states:

Tkinter — Writing Tk applications with Python2 (or Python 3.x)


But my assumption is that PyCharm created it’s own virtualenv for you project, so you are probably using wrong python interpreter in PyCharm.

Open your PyCharm project. Go to File->Settings->Project->Project Interpreter. At top, you will see what python interpreter is PyCharm using for a current project. If that’s not the system one you have, find path to system interpreter and add it to Python Interpreters in PyCharm.

More details on PyCharm Documentation.

answered Dec 16, 2018 at 9:18

Dinko Pehar's user avatar

Dinko PeharDinko Pehar

5,0663 gold badges21 silver badges49 bronze badges

1

Pycharm is having problems with tkinter probably because you’re using the flatpak version. I had the same problem with Pycharm as well as VSCode. It wouldn’t recognize module tkinter. I tried using the snap version of Pycharm and now it is working perfectly fine. I think you should give it a try before looking for tkinter.

sudo snap install pycharm-community --classic

answered Oct 13, 2022 at 12:31

Anukaran Subedi's user avatar

Python already has tkinter installed. It is a base module, like random or time, therefore you don’t need to install it.

answered Dec 15, 2018 at 22:16

Sam's user avatar

2

To install tkinter in Pycharm, install the module “future” and restart pycharm. Tkinter will be imported, to access it use:

from future.moves import tkinter

If it don’t work for you, search where tkinter lies in «future» package using cmd:

$ find . -name "*tkinter*"

and import accordingly.

answered Jun 9, 2020 at 13:22

Ritesh Mishra's user avatar

1

Pycharm comes with tkinter by default. But there are some circumstances that your installation might be missing tkinter. In that case you have to follow below mentioned steps.

For python 2 use:

sudo apt-get install python-tk

For python 3 use:

sudo apt-get install python3-tk

When you display info about packages it states:

Basically you have to import it

from tkinter import *

top = Tk()
# Code to add widgets will go here...
top.mainloop()

answered Feb 15, 2020 at 10:33

Tharindu Kumara's user avatar

Tharindu KumaraTharindu Kumara

4,3782 gold badges26 silver badges46 bronze badges

For Python 3.8:

sudo apt-get install python3.8-tk

mbomb007's user avatar

mbomb007

3,6452 gold badges40 silver badges67 bronze badges

answered Dec 23, 2020 at 16:17

Gabriel Stremțan's user avatar

Tkinter is a Python library that allows you to write GUI interfaces for Windows, Unix, and Linux operating systems.

Problem Formulation: Given a PyCharm project. How to install the Tkinter library in your project within a virtual environment or globally?

The Tkinter library is built-in with every Python installation, so it’s already installed in PyCharm per default. This means that you have to do nothing else but to run “import tkinter” or “import tkinter as tk” in your Python 3 script without installation.

import tkinter
Install Tkinter Python PyCharm

(Just ignore the AttributeError in the console—I tried to check the TKinter version but it didn’t have the __version__ attribute. ? )

If just importing the Tkinter library doesn’t work for you, chances are that you’re using Python 2 in which case you may want to try the capitalized form “import Tkinter” like so:

import Tkinter

Of course, you can also try to manually install Tkinter in the PyCharm “Terminal” view using either of the following:

  • pip install python-tk
  • pip install python3-tk
  • sudo apt-get install python-tk
  • sudo apt-get install python3-tk

Feel free to check out the following free email academy with Python cheat sheets to boost your coding skills!

To become a PyCharm master, check out our full course on the Finxter Computer Science Academy available for free for all Finxter Premium Members:

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. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, 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.

Установка Python

Python существует в нескольких разных версиях, с разными вариантами конфигурации в каждой операционной системе. Это приложение пригодится вам в том случае, если описание из главы 1 не сработало или вы захотите установить другую версию Python вместо той, которая поставлялась с вашей системой.

Python в Windows

Python обычно не включается в установку Windows по умолчанию, и все же вам стоит проверить, присутствует ли Python в вашей системе. Также можно открыть окно командой меню Пуск (Start). В открывшемся терминальном окне введите команду:

Если вы получили подобный результат:

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

Установка Python 3 в Windows

Откройте страницуopen in new window, щелкните на кнопке Download Python.

скрин_сайта

После скачивания запустите программу установки. В окне настройки установки нужно установить флажок Add Python to PATH. Это необходимо для дальнейшего удобства запуска Python программ.

add_Python_3.5_path

После установки можно ещё раз проверить какая версия Python установилась. Напечатав в командной строке виндос команду, которая вам уже знакома:

Если вы получили подобный результат:

значит, язык Python уже установлен в вашей системе.

Редакторы кода

Программисты проводят много времени за написанием, чтением и редактированием кода. Очень важно, чтобы в используемом текстовом редакторе эта работа выполнялась по возможности эффективно. Эффективный редактор должен выделять структуру кода, чтобы вы могли обнаружить типичные ошибки во время работы. Также редактор должен поддерживать автоматическую расстановку отступов, маркеры для обозначения длины строки и комбинации клавиш для часто выполняемых операций.

Начинающему программисту рекомендуется использовать редактор, который поддерживает все эти функции, но не создает проблем на начальном этапе. Также желательно кое-что знать о более сложных редакторах, чтобы вы понимали, в какой момент можно задуматься над переходом.

IDLE

Это редактор, который поставляется с Python по умолчанию. Запустить данный редактор можно выполнив следующие команды для windows:

  1. нажмите на клавиатуре кнопку win (вместо надписи может быть изображение окошка) кнопка находиться в левом нижнем углу клавиатуры вторая слева от пробела.
  2. печатаем на клавиатуре слово: idle
  3. нажимаем Enter

Если все выполнили правильно вы увидите подобное окно:

.. image:: img/python3.6.3.idle.png :alt: python3.6.3.idle.png

Попробуйте в данном редакторе написать и запустить следующие программы:

  1. Напишите программу, которая выводит в консоль надпись: «Hello world!».
  2. Напишите программу, которая выводит в консоль надпись: «Hello moon!». Изначально выводимая фраза должна храниться в переменной с именем: text.

Если всё выполнено правильно, то вы можете увидеть подобный результат:

python3.6.5.idle_hello_world.png

PyCharm

Удобный бесплатный редактор который используется большим числом питон программистов. Скачать его можно на сайтеopen in new window

Комъюнити версия является бесплатной версией.

download_PyCharm.png

PyCharm — это полноценная среда разработки, поддерживающая несколько языков программирования и включает в себя ряд полезных инструментов, о которых вы будете узнавать по мере профессионального роста.

Интерфейс программы PyCharm может выглядеть следующим образом.

PyCharm.png

It gives me error when i run my «Tkinter» code.It says «Tk() was not defined». I tried to download Tkinter on PyCharm but there are a lot of them. Well, I don’t know what to do. Help please.

asked Apr 6, 2019 at 12:48

Matas Stankaitis's user avatar

2

Install future instead of Tkinter on Pycharm. In the Pycharm console, install future as

pip install future

after install is done, use below to import Tkinter

from future.moves import tkinter

Greenonline's user avatar

Greenonline

2,1388 gold badges23 silver badges30 bronze badges

answered Sep 3, 2020 at 13:39

10hero's user avatar

There’re lot ports of PySimpleGUI, basic one is PySimpleGUI which is tkinter port and all GUI code are based on tkinter module. Some other ports are based on Qt, WxPython, and Remi.

The tkinter package (“Tk interface”) is the standard Python interface to the Tk GUI toolkit. Both Tk and tkinter are available on most Unix platforms, as well as on Windows systems. (Tk itself is not part of Python; it is maintained at ActiveState.)

There’s one path shown in your output of sys.path,

C:UsersuserAppDataLocalProgramsPythonPython37-32lib

if nothing wrong, you can find the sub-directory tkinter and something like this,

 Directory of C:SoftwarePythonLibtkinter

2020/11/13  上午 04:00    <DIR>          .
2020/11/13  上午 04:00    <DIR>          ..
2017/06/17  下午 07:57             1,863 colorchooser.py
2017/06/17  下午 07:57             1,302 commondialog.py
2017/06/17  下午 07:57             1,603 constants.py
2017/06/17  下午 07:57             1,555 dialog.py
2017/06/17  下午 07:57            11,809 dnd.py
2017/06/17  下午 07:57            14,981 filedialog.py
2017/06/17  下午 07:57             6,813 font.py
2017/06/17  下午 07:57             3,835 messagebox.py
2017/06/17  下午 07:57             1,868 scrolledtext.py
2017/06/17  下午 07:57            11,847 simpledialog.py
2020/11/13  上午 04:00    <DIR>          test
2017/06/17  下午 07:57            79,034 tix.py
2017/06/17  下午 07:57            58,630 ttk.py
2017/06/17  下午 07:57           170,821 __init__.py
2017/06/17  下午 07:57               155 __main__.py
2020/11/21  下午 03:07    <DIR>          __pycache__
              14 File(s)        366,116 bytes
               4 Dir(s)  45,897,330,688 bytes free

I just installed Pycharm Community 2020.3 yesterday, not install any package from Available Packages and everything ready.

image

Библиотека Tkinter

Библиотека Tkinter установлена
в Python в качестве стандартного модуля, поэтому нам не нужно устанавливать
что-либо для его использования. Tkinter — очень мощная библиотека. Мы
используем Python 3.9 поэтому, если при применении Python 2.x, этой библиотеки
не существует.

Создание окна

1.Создание
окна

Набираем
следующую программу:

from tkinter import *

window = Tk()

window.title(«Добро
пожаловать в приложение
Prodject«)

window.mainloop()

Рис.1.

После
запуска получаем следующее окно:

Рис.2.

Последняя
строка набранной программы
window.mainloop() вызывает функцию mainloop. Эта функция вызывает бесконечный цикл окна, поэтому окно
будет ждать любого взаимодействия с пользователем, пока не будет закрыто.
 Если в программе не прописать (вызвать) функцию mainloop, то для пользователя
на экране ничего не отобразится.

Добавление
текста в окно проекта (создание виджета Label)

Чтобы добавить текст в
проект, создадим 
lbl , с помощью класса Label, например:

lbl = Label(window, text="Привет")
 

Установка позиции
текста в окне осуществляем с помощью функции 
grid и
укажем ее следующим образом:

lbl.grid(column=0, row=0)
 

Пример окончательного кода,
будет выглядеть следующим образом:

 
from tkinter import *  
  
  
window = Tk()  
window.title("Добро пожаловать в приложение Prodject")  
lbl = Label(window, text="Проект")  
lbl.grid(column=0, row=0)  
window.mainloop()
 

Рис.3.

 

Получаем результат:

Рис.4.

Если функция grid не
будет вызвана, текст на экране не будет отображаться.

 

Установка типа шрифта и его размера

С помощью библиотеки Tkinter можно задать тип шрифта текста и его размер.
Для изменения стиля шрифта оформить параметр 
font таким образом:

lbl = Label(window, text="Проект", font=("Times New Roman", 50))
Рис.5.
 

Рис.6.

Параметр font может быть передан любому виджету,
для того, чтобы поменять его шрифт, он применяется не только к 
Label.

Понравилась статья? Поделить с друзьями:
  • Как установить tizen studio на windows 10
  • Как установить vcruntime140 dll для windows 10 x64
  • Как установить tis bmw на windows 10 64 bit
  • Как установить vcp6 на windows 10
  • Как установить vcp драйвер на windows 10