Полный курс по изучению Tkinter + Примеры. Создание графического интерфейса на Python с Tkinter. Обучение Python GUI
Полный курс по изучению Tkinter + Примеры. Создание графического интерфейса на Python с Tkinter. Обучение Python GUI
Графический интерфейс – неотъемлемая составляющая любого современного приложения. Даже во времена MS DOS, несмотря на тотальное доминирование командной строки в те времена, все равно начали появляться первые графические интерфейсы. Чего только стоит легендарный файловый менеджер Norton Commander? А для создания игр работа с графическими интерфейсами вообще является приоритетной.
В Python работа с графическими интерфейсами осуществляется с помощью библиотеки Tkinter. Она предустановлена в язык, поэтому ее можно использовать сразу, без дополнительной установки.
Пример приложения, созданного с применением Tkinter – IDLE. Это очень популярная среда разработки приложений для Python.
Рекомендуется пользоваться Python 3.7 для того, чтобы проверять нашу инструкцию. Дело в том, что третья версия претерпела настолько существенные изменения, что использование второй версии уже далеко от реального программирования.
В этой инструкции мы будем подразумевать, что базовое представление о Python у Вас уже есть. Мы же будем говорить о том, как создавать окно, что такое виджеты и как их добавить и редактировать. Давайте начинать.
Создаем свой первый графический интерфейс
Перед тем, как использовать эту библиотеку, ее следует импортировать. После этого уже можно прописывать строки для настройки окна.
from tkinter import *
window = Tk()
window.title(«Добро пожаловать в приложение Python»)
window.mainloop()
Все, теперь мы создали приложение с графической оболочкой. Поздравляем.
Обратите внимание на последнюю строку . Она содержит метод mainloop() , который принадлежит объекту window . Она нужна для того, чтобы зациклить отображение окна. Если ее не использовать, то окно сразу закроется, и пользователь ничего не увидит.
Создаем виджет Label
Окно – это, конечно, прекрасно. Но что делать, если нам надо отобразить в нем какую-то надпись? Например, слово «Привет». Как это сделать?
Сначала необходимо добавить виджет. Для этого объявляется переменная (в нашем случае – lbl ) с использованием следующего кода.
После этого мы задаем место, в котором будет размещаться наша надпись. В нашем случае это будет самый верх окна слева. Соответственно, необходимо задать такое положение:
lbl.grid(column=0, row=0)
После того, как мы добавим эти строки в приведенный выше код (а добавлять их надо после той строки, где задается заголовок), получится следующий.
from tkinter import *
window = Tk()
window.title(«Добро пожаловать в приложение Python»)
lbl.grid(column=0, row=0)
window.mainloop()
Настраиваем размер и шрифт текста
Tkinter – гибкая библиотека. В том числе, в ней можно редактировать текст, задавая произвольный тип шрифта и его размер. Для этого в скобках объекта Label задается свойство font . Характеристики в скобках записываются в следующей последовательности: сначала – начертание шрифта, а потом – его размер. Например, если указать шрифт «Arial Bold» 50 размера, то окно с нашей надписью будет уже поинтереснее.
Этот параметр может использоваться, в том числе, и для других виджетов. Его можно применять не только к надписи. Если в виджете есть шрифт, его можно изменять.
Настраиваем размеры окна приложения
Программа у нас получилась отличная, конечно. Но, скажите, чего-то не хватает. Все правильно, окошко хотелось бы побольше. Что можно сделать для того, чтобы увеличить его?
Чтобы это сделать, используется метод geometry с аргументом в виде размеров окна, записанных в виде строки в формате «ширина»х«высота».
Например, так.
window.geometry(‘500×350’)
Эта строка делает размер окна по ширине 500 пикселей, а по высоте – 250.
Tkinter example.
package (“Tk interface”) is the standard Python interface to
the Tk GUI toolkit. Both Tk andare available on most Unix
platforms, as well as on Windows systems. (Tk itself is not part of Python; it
is maintained at ActiveState.) You can check thatis properly
installed on your system by running -m tkinter
from the command line;
this should open a window demonstrating a simple Tk interface.
See also
- Python Tkinter Resources
- The Python Tkinter Topic Guide provides a great deal of information on using Tk from Python and links to other sources of information on Tk.
- Extensive tutorial plus friendlier widget pages for some of the widgets.
- On-line reference material.
- Official manual for the latest tcl/tk version.
Theclass is instantiated without arguments. This creates a toplevel widget of Tk which usually is the main window of an application. Each instance has its own associated Tcl interpreter.
tkinter.
Tcl
( screenName=None , baseName=None , className='Tk' , useTk=0 )-
Thefunction is a factory function which creates an object much like that created by theclass, except that it does not initialize the Tk subsystem. This is most often useful when driving the Tcl interpreter in an environment where one doesn’t want to create extraneous toplevel windows, or where one cannot (such as Unix/Linux systems without an X server). An object created by theobject can have a Toplevel window created (and the Tk subsystem initialized) by calling its
loadtk()
method. - Text widget with a vertical scroll bar built in.
tkinter.colorchooser
- Dialog to let the user choose a color.
tkinter.commondialog
- Base class for the dialogs defined in the other modules listed here.
tkinter.filedialog
- Common dialogs to allow the user to specify a file to open or save.
tkinter.font
- Utilities to help work with fonts.
tkinter.messagebox
- Access to standard Tk dialog boxes.
tkinter.simpledialog
- Basic dialogs and convenience functions.
tkinter.dnd
- Drag-and-drop support for. This is experimental and should become deprecated when it is replaced with the Tk DND.
- Turtle graphics in a Tk window.
25.1.1. Tkinter Modules
Most of the time,is all you really need, but a number of
additional modules are available as well. The Tk interface is located in a
binary module named _tkinter
. This module contains the low-level
interface to Tk, and should never be used directly by application programmers.
It is usually a shared library (or DLL), but might in some cases be statically
linked with the Python interpreter.
In addition to the Tk interface module,includes a number of
Python modules, tkinter.constants
being one of the most important.
Importingwill automatically import tkinter.constants
,
so, usually, to use Tkinter all you need is a simple import statement:
Other modules that provide Tk support include:
From Tkinter import. Building Your First Python GUI Application With Tkinter
The foundational element of a Tkinter GUI is the window . Windows are the containers in which all other GUI elements live. These other GUI elements, such as text boxes, labels, and buttons, are known as widgets . Widgets are contained inside of windows.
First, create a window that contains a single widget. Start up a newsession and follow along!
Note: The code examples in this tutorial have all been tested on Windows, macOS, and Ubuntu Linux 20.04 with Python version 3.10.
If you’ve installed Python with the official installers available for Windows and macOS from python.org , then you should have no problem running the sample code. You can safely skip the rest of this note and continue with the tutorial!
If you haven’t installed Python with the official installers, or there’s no official distribution for your system, then here are some tips for getting up and going.
Python on macOS with Homebrew:
The Python distribution for macOS available on Homebrew doesn’t come bundled with the Tcl/Tk dependency required by Tkinter. The default system version is used instead. This version may be outdated and prevent you from importing the Tkinter module. To avoid this problem, use the official macOS installer .
Ubuntu Linux 20.04:
To conserve memory space, the default version of the Python interpreter that comes pre-installed on Ubuntu Linux 20.04 has no support for Tkinter. However, if you want to continue using the Python interpreter bundled with your operating system, then install the following package:
$ sudo apt-get install python3-tk
This installs the Python GUI Tkinter module.
Other Linux Flavors:
If you’re unable to get a working Python installation on your flavor of Linux, then you can build Python with the correct version of Tcl/Tk from the source code. For a step-by-step walk-through of this process, check out the. You may also try using pyenv to manage multiple Python versions.
Tkinter виджеты. Python Tkinter Widgets
In this tutorial, we will cover an overview of Tkinter widgets in Python. These widgets are the functional units on any Tkinter GUI application.
Tkinter Widgets
There are various controls, such as buttons , labels , scrollbars , radio buttons , and text boxes used in a GUI application. These little components or controls of Graphical User Interface (GUI) are known as widgets in Tkinter.
These are 19 widgets available in Python Tkinter module. Below we have all the widgets listed down with a basic description:
Name of Widget | Description |
---|---|
Button | If you want to add a button in your application then Button widget will be used. |
Canvas | To draw a complex layout and pictures (like graphics, text, etc.) Canvas Widget will be used. |
CheckButton | If you want to display a number of options as checkboxes then Checkbutton widget is used. It allows you to select multiple options at a time. |
Entry | To display a single-line text field that accepts values from the user Entry widget will be used. |
Frame | In order to group and organize another widgets Frame widget will be used. Basically it acts as a container that holds other widgets . |
Label | To Provide a single line caption to another widget Label widget will be used. It can contain images too. |
Listbox | To provide a user with a list of options the Listbox widget will be used. |
Menu | To provides commands to the user Menu widget will be used. Basically these commands are inside the Menubutton . This widget mainly creates all kinds of Menus required in the application. |
Menubutton | The Menubutton widget is used to display the menu items to the user. |
Message | The message widget mainly displays a message box to the user. Basically it is a multi-line text which is non-editable. |
Radiobutton | If you want the number of options to be displayed as radio buttons then the Radiobutton widget will be used. You can select one at a time. |
Scale | Scale widget is mainly a graphical slider that allows you to select values from the scale. |
Scrollbar | To scroll the window up and down the scrollbar widget in python will be used. |
Text | The text widget mainly provides a multi-line text field to the user where users and enter or edit the text and it is different from Entry. |
Toplevel | The Toplevel widget is mainly used to provide us with a separate window container |
SpinBox | |
PanedWindow | The PanedWindow is also a container widget that is mainly used to handle different panes . Panes arranged inside it can either Horizontal or vertical |
LabelFrame | The LabelFrame widget is also a container widget used to mainly handle the complex widgets. |
MessageBox | The MessageBox widget is mainly used to display messages in the Desktop applications. |
Tkinter Install. Pip Install Tkinter
The “Tkinter” package/library of python is used to develop the Graphical User Interfaces of python-based applications with great ease and control. What most people don’t realize is that the Tkinter package comes pre-installed in python 3.7 or higher, and if that is not the case, then it can be separately downloaded using the Pip commands.
Pre-requisites
There are a few pre-reqs for installing and using the Tkinter Package, and these pre-reqs include:
Python
Python must be installed in the user’s PC to not only install Tkinter but also to use it. To verify if python is installed on the PC or not, run the following command inside a Command Prompt or any other terminal:
python --version
The above command will produce the following results if python is installed:
Pip
pip --version
The output confirms that pip is installed on the user’s PC.
Check for Built-in Tkinter Package
As mentioned above, the Tkinter package also comes pre-installed with python 3.7 and higher. This essentially means that the user might not need to explicitly install the Tkinter package as it may already be installed on his machine. To verify this, run the following command inside the Command Prompt:
python -m tkinter
If the tkinter package is already installed, then the above command will result in the following output:
If the output is an error, then that means that the tkinter package is not pre-installed on your PC.
Installing Tkinter with Pip
Once you have made sure that you have all the prerequisites installed and also that there is no built-in tkinter with your python package, simply install the Tkinter using the following pip command:
pip install tk
Alternatively, you can also use the following command:
pip install tkinter
Both of the above commands will download and install the Tkinter package on your PC:
Testing the Tkinter Package
After that, import the tkinter package and launch a new frame using the following lines:
import tkinter
tkinter._test ( )
After that, the following window will open up:
The window contains a demo GUI from the tkinter package, which contains two buttons, “Click me!” and “QUIT,” and two statements that display the version of the TK or the TCL package. The current version installed is the “ Tcl 8.6 ”
Conclusion
The “pip install tkinter” command is used to install the tkinter package in python, a Graphical User Interface builder package that provides many features to the developer. However, this Tkinter package, also known as Tcl or TK package, comes as a built-in module with python 3.7 and higher. Therefore, the user might not necessarily need to install the tkinter package separately. This post has pictorially represented the purpose and the usage for the “pip install tkinter” command.