Well I can see two solutions here:
1) Follow the Docs-Tkinter install for Python (for Windows):
Tkinter (and, since Python 3.1, ttk) are included with all standard Python distributions. It is important that you use a version of Python supporting Tk 8.5 or greater, and ttk. We recommend installing the «ActivePython» distribution from ActiveState, which includes everything you’ll need.
In your web browser, go to Activestate.com, and follow along the links to download the Community Edition of ActivePython for Windows. Make sure you’re downloading a 3.1 or newer version, not a 2.x version.
Run the installer, and follow along. You’ll end up with a fresh install of ActivePython, located in, e.g. C:python32
. From a Windows command prompt, or the Start Menu’s «Run…» command, you should then be able to run a Python shell via:
% C:python32python
This should give you the Python command prompt. From the prompt, enter these two commands:
>>> import tkinter
>>> tkinter._test()
This should pop up a small window; the first line at the top of the window should say «This is Tcl/Tk version 8.5»; make sure it is not 8.4!
2) Uninstall 64-bit Python and install 32 bit Python.
Tkinter – это стандартная библиотека Python, которая используется для приложения с графическим интерфейсом. Tkinter с Python предлагает простой и быстрый способ создания приложений с графическим интерфейсом.
Tk GUI работает на основе объектно-ориентированного подхода, что делает его мощной библиотекой. Tkinter широко доступен для всех операционных систем. Он предварительно установлен в Python. Для работы с Tkinter мы должны установить Python. В этом руководстве мы узнаем, как установить Tkinter в Python для Windows.
Чтобы создать удобное приложение с графическим интерфейсом пользователя, вы должны иметь базовые знания языка программирования Python.
Tkinter поставляется с установщиком Python. Нам просто нужно установить Python с www.python.org, Tkinter идет вместе с Python. Устанавливать отдельно не нужно. Установите флажок tcl / tk и IDE.
Чтобы проверить Tkinter, нам просто нужно импортировать его в текстовый редактор или IDE.
import tkinter as tk
Теперь мы можем получить доступ к его функциям для создания виджета. Давайте разберемся в следующем.
Пример –
from tkinter import * root = Tk() # Code to add widget will go here…….. w = Label(root, width = "40", height = "15") w.pack() root.mainloop()
Выход:
Все элементы будут размещены в этом окне Tkinter.
Изучаю Python вместе с вами, читаю, собираю и записываю информацию опытных программистов.
- Install Tkinter on Windows
- Install Tkinter on Linux
- Install Tkinter on Mac Operating System
- Install Tkinter in Pycharm
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.
Click here to read more about Tkinter.
В этой статье вы прочитаете про библиотеку Tkinter которая поможет в создание графического интерфейса в Python, но это будет скорее быстрый старт, чем подробный разбор как всё сделать.
Также можете почитать статью «Где используется язык программирования Python», тоже очень полезная, особенно для новичков.
Установка библиотеки Tkinter:
Для того чтобы её установить, нужно прописать такую команду в терминале или в консоли Windows:
Теперь вы можете работать с ней.
Работа с библиотекой Tkinter:
Тут мы создадим простое оконное приложение, я не буду показывать слишком много всего, а только само .
Вот код просто окна:
from tkinter import * root = Tk() root.title(«Программа на Python») root.geometry(«400×300») root.mainloop() |
Как видите в начале мы импортируем что нам нужно, это модуль tkinter, который нужен для создания оконного приложения, потом инициализируем проект благодаря функции Tk(), всё что мы получим кладём в переменную root.
Дальше назначаем заголовок окна через метод root.title(), и размер этого окна через root.geometry(), тут вы можете заметить, что мы передаём строку, она должна быть формата «ШиринаxВысота», заметим, что икс не должен быть заглавным.
Ну и последние, запускаем программу, а точнее запускаем цикл, благодаря которой будет работать вся программа, через метод root.mainloop()
Запускаем скрипт, делается это как обычно в языке Python и вот что мы видим:
То есть это просто пустое окно, но уже видно, что можно создать полноценное приложение, надо только добавить форму, кнопки т.д., но об этом может в другой части.
Вывод:
В этой статье вы прочитали про библиотеку Tkinter которая поможет в создание графического интерфейса в Python, в будущем я скорее всего ещё появиться статьи на эту тему.
Подписываетесь на соц-сети:
Оценка:
Загрузка…
Также рекомендую:
Download Article
Download Article
Tkinter (Tk) is a Python default GUI and comes with the Python installation on Linux, Mac, and Windows. Since Tk comes with most Python installations, you don’t generally need to install it yourself. Since Python 2 and Python 3 vary so much, this wikiHow will show you how to install Tkinter with Python 3 on Windows, Linux, and Mac OS.
-
1
-
2
Download the free community edition of ActiveTcl 8.6. You may be prompted to create a free account to download. You’ll just need to provide your email and create a password to continue.
Advertisement
-
3
Run the installer. You’ll need to unpack the file from the download folder before running it. Just drag and drop the application into the Applications folder. When you’re done, you’ll have an application called “Wish 8.6” inside the Utilities folder of your Applications folder.
-
4
Launch Wish 8.6. You’ll see 2 windows open. One is titled “Console” and the other is titled “Wish.” You can type commands in “Console.”
-
5
Type % info patchlevel and press ⏎ Return. You should see something like “8.6.9.” This shows the currently installed version.
Advertisement
-
1
-
2
Download the free community edition of ActiveTcl 8.6. You may be prompted to create a free account to download. You’ll just need to provide your email and create a password to continue.
-
3
Run the installer. You’ll normally find it in your Downloads folder. When you’re done, you’ll have a TCL install in C:TCL if you didn’t change the default location.
-
4
Open Command Prompt. You can do this by searching “Cmd” in the Start Menu’s search bar.
-
5
Run Wish. The command to start it depends on where you installed Wish.
- For example, if you used the default location when you downloaded ActiveTcl from the site, type % C:Tclbinwish86. Two windows will open. One is titled “Console” and the other is titled “Wish.”
-
6
Type % info patchlevel and press ↵ Enter. You should see something like “8.6.9,» which is the current installed and running version.
Advertisement
-
1
-
2
Download the free community edition of ActiveTcl 8.6. You may be prompted to create a free account to download. You’ll just need to provide your email and create a password to continue.
-
3
Run the installer. You’ll need to unpack the file from the download folder before running it. Just drag and drop the application into the Applications folder.
-
4
Press Ctrl+Alt+T to open a Terminal window.
-
5
Type % /opt/ActiveTcl-8.5/bin/wish8.6 to run Wish. A window will pop up titled “Wish 8.6.”
-
6
Type % info patchlevel and press ↵ Enter. This is to check the version of Wish you are running.[1]
Advertisement
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
Thanks for submitting a tip for review!
About This Article
Article SummaryX
1. Go to https://www.activestate.com/products/activetcl/tcl-tk-modules/.
2. Download and install the free community edition of ActiveTCL 8.6.
3. Launch Wish 8.6.
4. Type % info patchlevel» to make sure you have the right version.
Did this summary help you?
Thanks to all authors for creating a page that has been read 52,020 times.
Is this article up to date?
Download Article
Download Article
Tkinter (Tk) is a Python default GUI and comes with the Python installation on Linux, Mac, and Windows. Since Tk comes with most Python installations, you don’t generally need to install it yourself. Since Python 2 and Python 3 vary so much, this wikiHow will show you how to install Tkinter with Python 3 on Windows, Linux, and Mac OS.
-
1
-
2
Download the free community edition of ActiveTcl 8.6. You may be prompted to create a free account to download. You’ll just need to provide your email and create a password to continue.
Advertisement
-
3
Run the installer. You’ll need to unpack the file from the download folder before running it. Just drag and drop the application into the Applications folder. When you’re done, you’ll have an application called “Wish 8.6” inside the Utilities folder of your Applications folder.
-
4
Launch Wish 8.6. You’ll see 2 windows open. One is titled “Console” and the other is titled “Wish.” You can type commands in “Console.”
-
5
Type % info patchlevel and press ⏎ Return. You should see something like “8.6.9.” This shows the currently installed version.
Advertisement
-
1
-
2
Download the free community edition of ActiveTcl 8.6. You may be prompted to create a free account to download. You’ll just need to provide your email and create a password to continue.
-
3
Run the installer. You’ll normally find it in your Downloads folder. When you’re done, you’ll have a TCL install in C:TCL if you didn’t change the default location.
-
4
Open Command Prompt. You can do this by searching “Cmd” in the Start Menu’s search bar.
-
5
Run Wish. The command to start it depends on where you installed Wish.
- For example, if you used the default location when you downloaded ActiveTcl from the site, type % C:Tclbinwish86. Two windows will open. One is titled “Console” and the other is titled “Wish.”
-
6
Type % info patchlevel and press ↵ Enter. You should see something like “8.6.9,» which is the current installed and running version.
Advertisement
-
1
-
2
Download the free community edition of ActiveTcl 8.6. You may be prompted to create a free account to download. You’ll just need to provide your email and create a password to continue.
-
3
Run the installer. You’ll need to unpack the file from the download folder before running it. Just drag and drop the application into the Applications folder.
-
4
Press Ctrl+Alt+T to open a Terminal window.
-
5
Type % /opt/ActiveTcl-8.5/bin/wish8.6 to run Wish. A window will pop up titled “Wish 8.6.”
-
6
Type % info patchlevel and press ↵ Enter. This is to check the version of Wish you are running.[1]
Advertisement
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
Thanks for submitting a tip for review!
About This Article
Article SummaryX
1. Go to https://www.activestate.com/products/activetcl/tcl-tk-modules/.
2. Download and install the free community edition of ActiveTCL 8.6.
3. Launch Wish 8.6.
4. Type % info patchlevel» to make sure you have the right version.
Did this summary help you?
Thanks to all authors for creating a page that has been read 52,020 times.
Is this article up to date?
Getting Started
Tkinter is a wrapper around a GUI toolkit called Tk. It’s usually used
through a language called Tcl, but tkinter allows us to use Tcl and Tk
through Python. This means that we can use Tcl’s libraries like Tk with
Python without writing any Tcl code.
Installing tkinter
If you installed Python yourself you already have tkinter. If you
are using Linux you probably don’t, but you can install tkinter with
your distribution’s package manager. For example, you can use this
command on Debian-based distributions, like Ubuntu and Mint:
sudo apt install python3-tk
Hello World!
That’s enough talking. Let’s do the classic Hello World program
import tkinter root = tkinter.Tk() label = tkinter.Label(root, text="Hello World!") label.pack() root.mainloop()
Run this program like any other program. It should display a tiny window
with the text Hello World!
in it. I’m way too lazy to take
screenshots, so here’s some ASCII art:
,------------------.
| tk | _ | o | X |
|------------------|
| Hello World! |
`------------------'
There are many things going on in this short code. Let’s go through it
line by line.
Many other tkinter tutorials use from tkinter import *
instead, and then they
use things like Label
instead of tk.Label
. Don’t use star imports. It
will confuse you and other people. You can’t be sure about where Label
comes
from if the file is many lines long, but many tools that process code
automatically will also be confused. Overall, star imports are evil.
Some people like to do import tkinter as tk
and then use tk.Label
instead
of tkinter.Label
. There’s nothing wrong with that, and you can do that too if
you want to. It’s also possible to do from tkinter import Tk, Label, Button
,
which feels a little bit like a star import to me, but it’s definitely not as
bad as a star import.
The root window is the main window of our program. In this case, it’s
the only window that our program creates. Tkinter starts Tcl when you
create the root window.
label = tkinter.Label(root, text="Hello World!")
Like most other GUI toolkits, Tk uses widgets. A widget is something
that we see on the screen. Our program has two widgets. The root window
is a widget, and this label is a widget. A label is a widget that just
displays text.
Note that most widgets take a parent widget as the first argument.
When we do tk.Label(root)
, the root window becomes the parent so the
label will be displayed in the root window.
This adds the label into the root window so we can see it.
Instead of using a label
variable, you can also do this:
tkinter.Label(root, text="Hello World!").pack()
But don’t do this:
label = tkinter.Label(root, text="Hello World!").pack() # this is probably a mistake
Look carefully, the above code creates a label, packs it, and then sets a
label
variable to whatever the .pack()
returns. That is not same as the
label widget. It is None
because most functions return None
when they don’t
need to return anything more meaningful (I have written more about this
here), so you’ll get errors like
NoneType object something something
when you try to use the label
(see
here).
Anyway… let’s continue going through the lines of our example code.
The code before this takes usually just a fraction of a second to run,
but this line of code runs until we close the window. It’s usually
something between a few seconds and a few hours.
Hello Ttk!
There is a Tcl library called Ttk, short for «themed tk». I’ll show you why you
should use it instead of the non-Ttk code soon.
The tkinter.ttk
module contains things for using Ttk with Python. Here is a
tkinter program that displays two buttons that do nothing when they are
clicked. One of the buttons is a Ttk button and the other isn’t.
import tkinter from tkinter import ttk root = tkinter.Tk() tkinter.Button(root, text="Click me").pack() ttk.Button(root, text="Click me").pack() root.mainloop()
The GUI looks like this on Windows 7:
The ttk button is the one that looks a lot better. Tk itself is very old, and
its button widget is probably just as old, and it looks very old too. Ttk
widgets look much better in general, and you should always use Ttk widgets.
tl;dr: Use ttk.
If you already have some code that doesn’t use Ttk widgets, you just need to
add from tkinter import ttk
and then replace tkinter.SomeWidget
with
ttk.SomeWidget
everywhere. Most things will work just fine.
Unfortunately writing Ttk code is kind of inconvenient because there’s no way
to create a root window that uses Ttk. Some people just create a Tk root
window and add things to that, e.g. like this:
import tkinter from tkinter import ttk root = tkinter.Tk() ttk.Label(root, text="Hello!").pack() ttk.Button(root, text="Click me").pack() root.mainloop()
GUIs like this look horrible on my Linux system.
The background of this root window is not using Ttk, so it has very different
colors than the Ttk widgets. We can fix that by adding a big Ttk frame to the
Tk root window. A frame is an empty widget, and we can add any other widgets we
want inside a frame. If we add a ttk.Frame
to the root window and pack it
with fill='both', expand=True
, it will always fill the entire window, making
the window look like a Ttk widget. I’ll do this in all examples from now on.
root = tkinter.Tk() big_frame = ttk.Frame(root) big_frame.pack(fill='both', expand=True) # now add all widgets to big_frame instead of root
This is annoying, but keep in mind that you only need to do this once for each
window; in a big project you typically have many widgets inside each window,
and this extra boilerplate doesn’t annoy that much after all.
Here is a complete hello world program. It shouldn’t look too horrible on
anyone’s system.
import tkinter from tkinter import ttk root = tkinter.Tk() big_frame = ttk.Frame(root) big_frame.pack(fill='both', expand=True) label = ttk.Label(big_frame, text="Hello World!") label.pack() root.mainloop()
Tkinter and the >>>
prompt
The >>>
prompt is a great way to experiment with things. You can also
experiment with tkinter on the >>>
prompt, but unfortunately it
doesn’t work that well on all platforms. Everything works great on
Linux, but on Windows the root window is unresponsive when
root.mainloop()
is not running.
Try the hello world example on the >>>
prompt, just type it there line
by line. It’s really cool to see the widgets appearing on the screen as
you type. If this works on your system, that’s great! If not,
you can run root.update()
regularly to make it display your changes.
Print issues
If you try to print a tkinter widget, the results can be surprising.
Doing the same thing looks roughly like this on Python 3.5 and older:
>>> print(label) .3071874380
Here .!label
and .3071874380
were Tcl’s variable names. Converting a
widget to a string like str(widget)
gives us the widget’s Tcl variable
name, and print converts everything to strings using str()
.
>>> label <tkinter.Label object at 0xb72aa96c> >>> str(label) '.3073026412' >>> print(label) # same as print(str(label)) .3073026412
So if you’re trying to print a variable and you get something like
.!label
or .3071874380
, it’s probably a tkinter widget. You can also
check that with print(repr(something))
, it does the same thing as
looking at the widget on the >>>
prompt:
>>> print(repr(label)) <tkinter.Label object at 0xb72aa96c>
Widget options
When we created a label like label = tk.Label(root, text="Hello World!")
,
we got a label that displayed the text «Hello World!». Here text
was
an option, and its value was "Hello World!"
.
We can also change the text after creating the label in a few different
ways (we’ll find this useful later):
>>> label['text'] = "New text" # it behaves like a dict >>> label.config(text="New text") # this does the same thing >>> label.configure(text="New text") # this does the same thing too
The config
and configure
methods do the same thing, only their names
are different.
It’s also possible to get the text after setting it:
>>> label['text'] # again, it behaves like a dict 'New text' >>> label.cget('text') # or you can use a method instead 'New text'
There are multiple different ways to do the same things, and you can mix them
however you want. Personally I like to use initialization arguments and
treat the widget as a dict, but you can do whatever you want.
You can also convert the label to a dict to see all of the options and
their values:
>>> dict(label) {'padx': <pixel object: '1'>, 'pady': <pixel object: '1'>, 'borderwidth': <pixe l object: '1'>, 'cursor': '', 'state': 'normal', 'image': '', 'bd': <pixel obje ct: '1'>, 'font': 'TkDefaultFont', 'justify': 'center', 'height': 0, 'highlight color': '#ffffff', 'wraplength': <pixel object: '0'>, 'activebackground': '#ece cec', 'foreground': '#ffffff', 'anchor': 'center', 'bitmap': '', 'fg': '#ffffff ', 'compound': 'none', 'textvariable': '', 'underline': -1, 'background': '#3b3 b3e', 'width': 0, 'highlightbackground': '#3b3b3e', 'relief': 'flat', 'bg': '#3 b3b3e', 'text': '', 'highlightthickness': <pixel object: '0'>, 'takefocus': '0' , 'disabledforeground': '#a3a3a3', 'activeforeground': '#000000'}
That’s a mess! Let’s use
pprint.pprint:
>>> import pprint >>> pprint.pprint(dict(label)) {'activebackground': '#ececec', 'activeforeground': '#000000', 'anchor': 'center', 'background': '#3b3b3e', ...
If you are wondering what an option does you can just try it and see, or
you can read the manual page (see below).
Manual pages
Tkinter is not documented very well, but there are many good manual
pages about Tk written for Tcl users. Tcl and Python are two different
languages, but Tk’s manual pages are easy to apply to tkinter code.
You’ll find the manual pages useful later in this tutorial.
This tutorial contains links to the manual pages, like this
ttk_label(3tk) link. There’s also a list of the manual
pages.
If you are using Linux and you want to read the manual pages on a
terminal, you can also install Tk’s manual pages using your package
manager. For example, you can use this command on Debian-based
distributions:
Then you can read the manual pages like this:
Summary
- Tkinter is an easy way to write cross-platform GUIs.
- Now you should have tkinter installed and you should know how to use
it on the>>>
prompt. - Don’t use star imports.
- Now you should know what a widget is.
- Use ttk widgets with
from tkinter import ttk
, and always create a big
ttk.Frame
packed withfill='both', expand=True
into each root window. - You can set the values of Tk’s options when creating widgets like
label = tk.Label(root, text="hello")
, and you can change them later
using any of these ways:label['text'] = "new text" label.config(text="new text") label.configure(text="new text")
- You can get the current values of options like this:
print(label['text']) print(label.cget('text'))
- If
print(something)
prints something weird, try
print(repr(something))
. - You can view all options and their values like
pprint.pprint(dict(some_widget))
. The options are explained in the
manual pages.
Tkinter is the de facto way in Python to create Graphical User Interfaces (GUIs). Installing Tkinter on Windows is as simple as installing Python 3.x since Tkinter is included in the Python 3 core.
However, if you want to take advantage of the latest version of Tkinter, you’ll need to install a version of Python that supports Tcl/Tk 8.5 or greater, as well as Ttk (Tile extension integrated into Tk), which is required in order to run the current Tk widget set.
- Python 3.7 or greater for Windows comes with everything you need to run Tk fully configured out-of-the-box.
- If you have Python 3.6 or an earlier version, you can simply upgrade to a newer Python version that includes the latest version of Tkinter.
Python Distributions with Tkinter
Popular Python distributions like ActivePython and Anaconda both come with Tkinter.
The simplest method to install Tkinter in a Windows environment is to download and install ActivePython 3.8 from here.
Alternatively, you can create and activate a Conda environment with Python 3.7 or greater that is integrated with the latest version of Tkinter.
1. To create a new Conda Python environment named <env_name> and install python 3.8, open an Anaconda Prompt or terminal and enter:
$ conda create --name <env_name> python=3.8
2. To activate the new environment that has Python 3.8, and switch to it, enter:
$ activate <env_name>
Verify Tkinter Installation
To verify whether Tkinter is installed ready to be loaded by Python, run the following code in a Python console:
>>> import tkinter >>> tkinter._test()
If Tkinter is installed and working correctly, a small popup window will appear. The first line at the top of the window should state, This is Tcl/Tk version 8.6.
Watch video demonstration here.
You can also verify the Tcl/Tk version used by Tkinter with the following code:
>>> import tkinter >>> tkinter.Tcl().eval('info patchlevel')
The output should be similar to:
>>> '8.6.9'
You can also run a test script to make sure that Tkinter is functioning correctly. For example:
>>> from tkinter import * >>> root = Tk() >>> test = Label(root, text="<message>") >>> test.pack() >>> root.mainloop()
If Tkinter is correctly installed, a small popup window displaying a message should appear.
Watch video demonstration: How to verify Tkinter installation on Windows
With deep roots in open source, and as a founding member of the Python Foundation, ActiveState actively contributes to the Python community. We offer the convenience, security and support that your enterprise needs while being compatible with the open source distribution of Python.
Download ActivePython Community Edition to get started or contact us to learn more about using ActivePython in your organization.
You can also start by trying our mini ML runtime for Linux or Windows that includes most of the popular packages for Machine Learning and Data Science, pre-compiled and ready to for use in projects ranging from recommendation engines to dashboards.