Что такое mainloop в python
Перейти к содержимому

Что такое mainloop в python

  • автор:

tkinter — Python interface to Tcl/Tk¶

The tkinter package (“Tk interface”) is the standard Python interface to the Tcl/Tk GUI toolkit. Both Tk and tkinter are available on most Unix platforms, including macOS, as well as on Windows systems.

Running python -m tkinter from the command line should open a window demonstrating a simple Tk interface, letting you know that tkinter is properly installed on your system, and also showing what version of Tcl/Tk is installed, so you can read the Tcl/Tk documentation specific to that version.

Tkinter supports a range of Tcl/Tk versions, built either with or without thread support. The official Python binary release bundles Tcl/Tk 8.6 threaded. See the source code for the _tkinter module for more information about supported versions.

Tkinter is not a thin wrapper, but adds a fair amount of its own logic to make the experience more pythonic. This documentation will concentrate on these additions and changes, and refer to the official Tcl/Tk documentation for details that are unchanged.

Tcl/Tk 8.5 (2007) introduced a modern set of themed user interface components along with a new API to use them. Both old and new APIs are still available. Most documentation you will find online still uses the old API and can be woefully outdated.

Extensive tutorial on creating user interfaces with Tkinter. Explains key concepts, and illustrates recommended approaches using the modern API.

Reference documentation for Tkinter 8.5 detailing available classes, methods, and options.

Comprehensive reference to each of the underlying Tcl/Tk commands used by Tkinter.

Additional documentation, and links to Tcl/Tk core development.

By Mark Roseman. (ISBN 978-1999149567)

By Alan Moore. (ISBN 978-1788835886)

By Mark Lutz; has excellent coverage of Tkinter. (ISBN 978-0596158101)

By John Ousterhout, inventor of Tcl/Tk, and Ken Jones; does not cover Tkinter. (ISBN 978-0321336330)

Architecture¶

Tcl/Tk is not a single library but rather consists of a few distinct modules, each with separate functionality and its own official documentation. Python’s binary releases also ship an add-on module together with it.

Tcl is a dynamic interpreted programming language, just like Python. Though it can be used on its own as a general-purpose programming language, it is most commonly embedded into C applications as a scripting engine or an interface to the Tk toolkit. The Tcl library has a C interface to create and manage one or more instances of a Tcl interpreter, run Tcl commands and scripts in those instances, and add custom commands implemented in either Tcl or C. Each interpreter has an event queue, and there are facilities to send events to it and process them. Unlike Python, Tcl’s execution model is designed around cooperative multitasking, and Tkinter bridges this difference (see Threading model for details).

Tk is a Tcl package implemented in C that adds custom commands to create and manipulate GUI widgets. Each Tk object embeds its own Tcl interpreter instance with Tk loaded into it. Tk’s widgets are very customizable, though at the cost of a dated appearance. Tk uses Tcl’s event queue to generate and process GUI events.

Themed Tk (Ttk) is a newer family of Tk widgets that provide a much better appearance on different platforms than many of the classic Tk widgets. Ttk is distributed as part of Tk, starting with Tk version 8.5. Python bindings are provided in a separate module, tkinter.ttk .

Internally, Tk and Ttk use facilities of the underlying operating system, i.e., Xlib on Unix/X11, Cocoa on macOS, GDI on Windows.

When your Python application uses a class in Tkinter, e.g., to create a widget, the tkinter module first assembles a Tcl/Tk command string. It passes that Tcl command string to an internal _tkinter binary module, which then calls the Tcl interpreter to evaluate it. The Tcl interpreter will then call into the Tk and/or Ttk packages, which will in turn make calls to Xlib, Cocoa, or GDI.

Tkinter Modules¶

Support for Tkinter is spread across several modules. Most applications will need the main tkinter module, as well as the tkinter.ttk module, which provides the modern themed widget set and API:

Construct a toplevel Tk widget, which is usually the main window of an application, and initialize a Tcl interpreter for this widget. Each instance has its own associated Tcl interpreter.

The Tk class is typically instantiated using all default values. However, the following keyword arguments are currently recognized:

When given (as a string), sets the DISPLAY environment variable. (X11 only)

Name of the profile file. By default, baseName is derived from the program name ( sys.argv[0] ).

Name of the widget class. Used as a profile file and also as the name with which Tcl is invoked (argv0 in interp).

If True , initialize the Tk subsystem. The tkinter.Tcl() function sets this to False .

If True , execute all X server commands synchronously, so that errors are reported immediately. Can be used for debugging. (X11 only)

Specifies the id of the window in which to embed the application, instead of it being created as an independent toplevel window. id must be specified in the same way as the value for the -use option for toplevel widgets (that is, it has a form like that returned by winfo_id() ).

Note that on some platforms this will only work correctly if id refers to a Tk frame or toplevel that has its -container option enabled.

Tk reads and interprets profile files, named . className .tcl and . baseName .tcl , into the Tcl interpreter and calls exec() on the contents of . className .py and . baseName .py . The path for the profile files is the HOME environment variable or, if that isn’t defined, then os.curdir .

The Tk application object created by instantiating Tk . This provides access to the Tcl interpreter. Each widget that is attached the same instance of Tk has the same value for its tk attribute.

The widget object that contains this widget. For Tk , the master is None because it is the main window. The terms master and parent are similar and sometimes used interchangeably as argument names; however, calling winfo_parent() returns a string of the widget name whereas master returns the object. parent/child reflects the tree-like relationship while master/slave reflects the container structure.

The immediate descendants of this widget as a dict with the child widget names as the keys and the child instance objects as the values.

tkinter. Tcl ( screenName = None , baseName = None , className = ‘Tk’ , useTk = False ) ¶

The Tcl() function is a factory function which creates an object much like that created by the Tk class, 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 the Tcl() object can have a Toplevel window created (and the Tk subsystem initialized) by calling its loadtk() method.

The modules that provide Tk support include:

Main Tkinter module.

Dialog to let the user choose a color.

Base class for the dialogs defined in the other modules listed here.

Common dialogs to allow the user to specify a file to open or save.

Utilities to help work with fonts.

Access to standard Tk dialog boxes.

Text widget with a vertical scroll bar built in.

Basic dialogs and convenience functions.

Themed widget set introduced in Tk 8.5, providing modern alternatives for many of the classic widgets in the main tkinter module.

A binary module that contains the low-level interface to Tcl/Tk. It is automatically imported by the main tkinter module, 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.

Python’s Integrated Development and Learning Environment (IDLE). Based on tkinter .

Symbolic constants that can be used in place of strings when passing various parameters to Tkinter calls. Automatically imported by the main tkinter module.

(experimental) Drag-and-drop support for tkinter . This will become deprecated when it is replaced with the Tk DND.

(deprecated) An older third-party Tcl/Tk package that adds several new widgets. Better alternatives for most can be found in tkinter.ttk .

Turtle graphics in a Tk window.

Tkinter Life Preserver¶

This section is not designed to be an exhaustive tutorial on either Tk or Tkinter. For that, refer to one of the external resources noted earlier. Instead, this section provides a very quick orientation to what a Tkinter application looks like, identifies foundational Tk concepts, and explains how the Tkinter wrapper is structured.

The remainder of this section will help you to identify the classes, methods, and options you’ll need in your Tkinter application, and where to find more detailed documentation on them, including in the official Tcl/Tk reference manual.

A Hello World Program¶

We’ll start by walking through a “Hello World” application in Tkinter. This isn’t the smallest one we could write, but has enough to illustrate some key concepts you’ll need to know.

After the imports, the next line creates an instance of the Tk class, which initializes Tk and creates its associated Tcl interpreter. It also creates a toplevel window, known as the root window, which serves as the main window of the application.

The following line creates a frame widget, which in this case will contain a label and a button we’ll create next. The frame is fit inside the root window.

The next line creates a label widget holding a static text string. The grid() method is used to specify the relative layout (position) of the label within its containing frame widget, similar to how tables in HTML work.

A button widget is then created, and placed to the right of the label. When pressed, it will call the destroy() method of the root window.

Finally, the mainloop() method puts everything on the display, and responds to user input until the program terminates.

Important Tk Concepts¶

Even this simple program illustrates the following key Tk concepts:

A Tkinter user interface is made up of individual widgets. Each widget is represented as a Python object, instantiated from classes like ttk.Frame , ttk.Label , and ttk.Button .

Widgets are arranged in a hierarchy. The label and button were contained within a frame, which in turn was contained within the root window. When creating each child widget, its parent widget is passed as the first argument to the widget constructor.

Widgets have configuration options, which modify their appearance and behavior, such as the text to display in a label or button. Different classes of widgets will have different sets of options.

Widgets aren’t automatically added to the user interface when they are created. A geometry manager like grid controls where in the user interface they are placed.

Tkinter reacts to user input, changes from your program, and even refreshes the display only when actively running an event loop. If your program isn’t running the event loop, your user interface won’t update.

Understanding How Tkinter Wraps Tcl/Tk¶

When your application uses Tkinter’s classes and methods, internally Tkinter is assembling strings representing Tcl/Tk commands, and executing those commands in the Tcl interpreter attached to your applicaton’s Tk instance.

Whether it’s trying to navigate reference documentation, trying to find the right method or option, adapting some existing code, or debugging your Tkinter application, there are times that it will be useful to understand what those underlying Tcl/Tk commands look like.

To illustrate, here is the Tcl/Tk equivalent of the main part of the Tkinter script above.

Tcl’s syntax is similar to many shell languages, where the first word is the command to be executed, with arguments to that command following it, separated by spaces. Without getting into too many details, notice the following:

The commands used to create widgets (like ttk::frame ) correspond to widget classes in Tkinter.

Tcl widget options (like -text ) correspond to keyword arguments in Tkinter.

Widgets are referred to by a pathname in Tcl (like .frm.btn ), whereas Tkinter doesn’t use names but object references.

A widget’s place in the widget hierarchy is encoded in its (hierarchical) pathname, which uses a . (dot) as a path separator. The pathname for the root window is just . (dot). In Tkinter, the hierarchy is defined not by pathname but by specifying the parent widget when creating each child widget.

Operations which are implemented as separate commands in Tcl (like grid or destroy ) are represented as methods on Tkinter widget objects. As you’ll see shortly, at other times Tcl uses what appear to be method calls on widget objects, which more closely mirror what would is used in Tkinter.

How do I…? What option does…?¶

If you’re not sure how to do something in Tkinter, and you can’t immediately find it in the tutorial or reference documentation you’re using, there are a few strategies that can be helpful.

First, remember that the details of how individual widgets work may vary across different versions of both Tkinter and Tcl/Tk. If you’re searching documentation, make sure it corresponds to the Python and Tcl/Tk versions installed on your system.

When searching for how to use an API, it helps to know the exact name of the class, option, or method that you’re using. Introspection, either in an interactive Python shell or with print() , can help you identify what you need.

To find out what configuration options are available on any widget, call its configure() method, which returns a dictionary containing a variety of information about each object, including its default and current values. Use keys() to get just the names of each option.

As most widgets have many configuration options in common, it can be useful to find out which are specific to a particular widget class. Comparing the list of options to that of a simpler widget, like a frame, is one way to do that.

Similarly, you can find the available methods for a widget object using the standard dir() function. If you try it, you’ll see there are over 200 common widget methods, so again identifying those specific to a widget class is helpful.

Navigating the Tcl/Tk Reference Manual¶

As noted, the official Tk commands reference manual (man pages) is often the most accurate description of what specific operations on widgets do. Even when you know the name of the option or method that you need, you may still have a few places to look.

While all operations in Tkinter are implemented as method calls on widget objects, you’ve seen that many Tcl/Tk operations appear as commands that take a widget pathname as its first parameter, followed by optional parameters, e.g.

Others, however, look more like methods called on a widget object (in fact, when you create a widget in Tcl/Tk, it creates a Tcl command with the name of the widget pathname, with the first parameter to that command being the name of a method to call).

In the official Tcl/Tk reference documentation, you’ll find most operations that look like method calls on the man page for a specific widget (e.g., you’ll find the invoke() method on the ttk::button man page), while functions that take a widget as a parameter often have their own man page (e.g., grid).

You’ll find many common options and methods in the options or ttk::widget man pages, while others are found in the man page for a specific widget class.

You’ll also find that many Tkinter methods have compound names, e.g., winfo_x() , winfo_height() , winfo_viewable() . You’d find documentation for all of these in the winfo man page.

Somewhat confusingly, there are also methods on all Tkinter widgets that don’t actually operate on the widget, but operate at a global scope, independent of any widget. Examples are methods for accessing the clipboard or the system bell. (They happen to be implemented as methods in the base Widget class that all Tkinter widgets inherit from).

Threading model¶

Python and Tcl/Tk have very different threading models, which tkinter tries to bridge. If you use threads, you may need to be aware of this.

A Python interpreter may have many threads associated with it. In Tcl, multiple threads can be created, but each thread has a separate Tcl interpreter instance associated with it. Threads can also create more than one interpreter instance, though each interpreter instance can be used only by the one thread that created it.

Each Tk object created by tkinter contains a Tcl interpreter. It also keeps track of which thread created that interpreter. Calls to tkinter can be made from any Python thread. Internally, if a call comes from a thread other than the one that created the Tk object, an event is posted to the interpreter’s event queue, and when executed, the result is returned to the calling Python thread.

Tcl/Tk applications are normally event-driven, meaning that after initialization, the interpreter runs an event loop (i.e. Tk.mainloop() ) and responds to events. Because it is single-threaded, event handlers must respond quickly, otherwise they will block other events from being processed. To avoid this, any long-running computations should not run in an event handler, but are either broken into smaller pieces using timers, or run in another thread. This is different from many GUI toolkits where the GUI runs in a completely separate thread from all application code including event handlers.

If the Tcl interpreter is not running the event loop and processing events, any tkinter calls made from threads other than the one running the Tcl interpreter will fail.

A number of special cases exist:

  • Tcl/Tk libraries can be built so they are not thread-aware. In this case, tkinter calls the library from the originating Python thread, even if this is different than the thread that created the Tcl interpreter. A global lock ensures only one call occurs at a time.

  • While tkinter allows you to create more than one instance of a Tk object (with its own interpreter), all interpreters that are part of the same thread share a common event queue, which gets ugly fast. In practice, don’t create more than one instance of Tk at a time. Otherwise, it’s best to create them in separate threads and ensure you’re running a thread-aware Tcl/Tk build.

  • Blocking event handlers are not the only way to prevent the Tcl interpreter from reentering the event loop. It is even possible to run multiple nested event loops or abandon the event loop entirely. If you’re doing anything tricky when it comes to events or threads, be aware of these possibilities.

  • There are a few select tkinter functions that presently work only when called from the thread that created the Tcl interpreter.

Handy Reference¶

Setting Options¶

Options control things like the color and border width of a widget. Options can be set in three ways:

Курс по библиотеке Tkinter языка Python

Этой библиотеке посвящено мало внимания, и найти в рунете курс, книгу или FAQ по ней довольно-таки сложно. Стоит отметить, что здесь отражены только основы этой библиотеки, и надеюсь, что более опытные люди дополнят эту статью.

Что такое Tkinter?

Tkinter (от англ. tk interface) — это графическая библиотека, позволяющая создавать программы с оконным интерфейсом. Эта библиотека является интерфейсом к популярному языку программирования и инструменту создания графических приложений tcl/tk. Tkinter, как и tcl/tk, является кроссплатформенной библиотекой и может быть использована в большинстве распространённых операционных систем (Windows, Linux, Mac OS X и др.).

Так как Tkinter является достаточно прозрачным интерфейсом к tcl/tk, то основным источником информации для неё являются man-страницы tcl/tk. Эти страницы имеются в любой Unix-системе (в разделе n или 3tk). Также они доступны онлайн на сайте http://tcl.tk. Основные:

Начиная с версии python-3.0 библиотека переименована в соответствии с PEP 8 в tkinter (с маленькой буквы).

Импортируется она как и любая другая библиотека:

В Tkinter визуальные контроллы называются виджетами (widget, от англ. window gadget) — стандартизированный компонент графического интерфейса, с которым взаимодействует пользователь.

Класс Tk

Tk является базовым классом любого Tkinter приложения. При создании объекта этого класса запускается интерпретатор tcl/tk и создаётся базовое окно приложения.

Tkinter является событийно-ориентированной библиотекой. В приложениях такого типа имеется главный цикл обработки событий. В Tkinter такой цикл запускается методом mainloop. Для явного выхода из интерпретатора и завершения цикла обработки событий используется метод quit.

Таким образом минимальное приложение на Tkinter будет таким:

В приложении можно использовать несколько интерпретаторов tcl/tk. Так как после вызова метода mainloop дальнейшие команды python исполняться не будут до выхода из цикла обработки событий, необходимо метод mainloop всех интерпретаторов кроме последнего осуществлять в фоновом режиме. Пример запуска двух интерпретаторов:

При использовании двух и более интерпретаторов необходимо следить, чтобы объекты, созданные в одном интерпретаторе, использовались только в нём. Например, изображение, созданное в первом интерпретаторе, может быть использовано много раз в этом же интерпретаторе, но не может быть использовано в других интерпретаторах. Необходимость в запуске нескольких интерпретаторов в одном приложении возникает крайне редко. Для создания дополнительного окна приложения в большинстве случаев достаточно виджета Toplevel.

Общее для всех виджетов

Все виджеты в Tkinter обладают некоторыми общими свойствами. Опишем их, перед тем как перейти к рассмотрению конкретных виджетов. Виджеты создаются вызовом конструктора соответствующего класса. Первый аргумент (как правило неименованный, но можно использовать имя master) это родительский виджет, в который будет упакован (помещён) наш виджет. Родительский виджет можно не указывать, в таком случае будет использовано главное окно приложения. Далее следуют именованные аргументы, конфигурирующие виджет. Это может быть используемый шрифт (font=. ), цвет виджета (bg=. ), команда, выполняющаяся при активации виджета (command=. ) и т.д. Полный список всех аргументов можно посмотреть в man options и man-странице соответствующего виджета (например man button, см. разделы «STANDARD OPTIONS» и «WIDGET-SPECIFIC OPTIONS»). Пример кода:

Памятуя о Zen Python (явное лучше неявного) указываю: данный код написан и работает для Python v 2. В случае использования Python v 3 код немного изменится. 1. tkinter с маленькой буквы. 2. print в круглых скобках () и без u.

Методы виджетов

Виджеты могут быть сконфигурированы во время создания, но иногда необходимо изменить конфигурацию виджета во время исполнения программы. Для этого используется метод configure (или его синоним config). Также можно использовать квадратные скобки (widget[‘option’] = new_value). Пример, программа выводит текущее время, после клика по кнопке:

В этом коде функция button_clicked вызывается каждый раз, когда пользователь кликает по кнопке.

Метод cget является обратным к методу configure. Он предназначен для получения информации о конфигурации виджета. Здесь как и в случае с configure можно использовать квадратные скобки (value = widget[‘option’]). Пример, после клика на кнопку программа показывает цвет кнопки и меняет его на другой:

Уничтожение виджета и всех его потомков. Стоит отметить, что если необходимо только на время спрятать какой-либо виджет, то лучше пользоваться упаковщиком grid и методом grid_remove:

Использование grid_remove позволяет сохранять взаимное расположение виджетов.

Методы семейства grab_ предназначены для управления потоком события. Виджет, захвативший поток, будет получать все события окна или приложения.

  • grab_set — передать поток данному виджету
  • grab_set_global — передать глобальный поток данному виджету. В этом случае все события на дисплее будут передаваться этому виджету. Следует пользоваться очень осторожно, т.к. остальные виджеты всех приложений не будут получать события.
  • grab_release — освободить поток
  • grab_status — узнать текущий статус потока событий для виджета. Возможные значения: None, «local» или «global».
  • grab_current — получить виджет, который получает поток

Пример, приложение захватывает глобальный поток и освобождает его через 10 секунд:

Методы семейства focus_ используются для управления фокусом ввода с клавиатуры. Виджет, имеющий фокус, получает все события с клавиатуры.

  • focus (синоним focus_set) — передать фокус виджету.
  • focus_force — передать фокус, даже если приложение не имеет фокуса. Используйте осторожно, поскольку это может раздражать пользователей.
  • focus_get — возвращает виджет, на который направлен фокус, либо None, если такой отсутствует.
  • focus_displayof — возвращает виджет, на который направлен фокус на том дисплее, на котором размещён виджет, либо None, если такой отсутствует.
  • focus_lastfor — возвращает виджет, на который будет направлен фокус, когда окно с этим виджетом получит фокус.
  • tk_focusNext — возвращает виджет, который получит фокус следующим (обычно смена фокуса происходит при нажатии клавиши Tab). Порядок следования определяется последовательностью упаковки виджетов.
  • tk_focusPrev — то же, что и focusNext, но в обратном порядке.
  • tk_focusFollowsMouse — устанавливает, что виджет будет получать фокус при наведении на него мышью. Вернуть нормальное поведение достаточно сложно.

«Системные» методы

Эти методы не являются виджет-специфичными, т.е. хотя они являются методами виджетов они влияют на работу интерпретатора tcl/tk.

after, after_idle и after_cancel [3]

Таймеры. С помощью этих методов вы можете отложить выполнение какого-нибудь кода на определённое время.

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

after_idle — принимает один аргумент — функцию. Эта функция будет выполнена после завершения всех отложенных операций (после того, как будут обработаны все события). Возвращает идентификатор, который может быть использован в after_cancel.

after_cancel — принимает один аргумент: идентификатор задачи, полученный предыдущими функциями, и отменяет это задание.

update и update_idletasks [4]

Две функции, для работы с очередью задач. Их выполнение вызывает обработку отложенных задач.

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

update обрабатывает все задачи, стоящие в очереди. Обычно эта функция используется во время «тяжёлых» расчётов, когда необходимо чтобы приложение оставалось отзывчивым на действия пользователя.

eval и evalfile

Две недокументированные функции для выполнения кода на tcl. eval позволяет выполнить строку на языке программирования tcl, а evalfile — выполнить код, записанный в файл. В качестве аргументов принимают соответственно строку и путь к файлу. Данные функции полезны при использовании дополнительных модулей, написанных на tcl. Пример:

Основные виджеты

Toplevel

Toplevel [5] — окно верхнего уровня. Обычно используется для создания многооконных программ, а также для диалоговых окон.

  • title — заголовок окна
  • overrideredirect — указание оконному менеджеру игнорировать это окно. Аргументом является True или False. В случае, если аргумент не указан — получаем текущее значение. Если аргумент равен True, то такое окно будет показано оконным менеджером без обрамления (без заголовка и бордюра). Может быть использовано, например, для создания splashscreen при старте программы.
  • iconify / deiconify — свернуть / развернуть окно
  • withdraw — «спрятать» (сделать невидимым) окно. Для того, чтобы снова показать его, надо использовать метод deiconify.
  • minsize и maxsize — минимальный / максимальный размер окна. Методы принимают два аргумента — ширина и высота окна. Если аргументы не указаны — возвращают текущее значение.
  • state — получить текущее значение состояния окна. Может возвращать следующие значения: normal (нормальное состояние), icon (показано в виде иконки), iconic (свёрнуто), withdrawn (не показано), zoomed (развёрнуто на полный экран, только для Windows и Mac OS X)
  • resizable — может ли пользователь изменять размер окна. Принимает два аргумента — возможность изменения размера по горизонтали и по вертикали. Без аргументов возвращает текущее значение.
  • geometry — устанавливает геометрию окна в формате ширинаxвысота+x+y (пример: geometry(«600×400+40+80») — поместить окно в точку с координатам 40,80 и установить размер в 600×400). Размер или координаты могут быть опущены (geometry(«600×400») — только изменить размер, geometry(«+40+80») — только переместить окно).
  • transient — сделать окно зависимым от другого окна, указанного в аргументе. Будет сворачиваться вместе с указанным окном. Без аргументов возвращает текущее значение.
  • protocol — получает два аргумента: название события и функцию, которая будет вызываться при наступлении указанного события. События могут называться WM_TAKE_FOCUS (получение фокуса), WM_SAVE_YOURSELF (необходимо сохраниться, в настоящий момент является устаревшим), WM_DELETE_WINDOW (удаление окна).
  • tkraise (синоним lift) и lower — поднимает (размещает поверх всех других окон) или опускает окно. Методы могут принимать один необязательный аргумент: над/под каким окном разместить текущее.
  • grab_set — устанавливает фокус на окно, даже при наличии открытых других окон
  • grab_release — снимает монопольное владение фокусом ввода с окна

Эти же методы могут быть использованы для корневого (root) окна.

Таким способом можно предотвратить закрытие окна (например, если закрытие окна приведёт к потере введённых пользователем данных).

Button

Виджет Button — самая обыкновенная кнопка, которая используется в тысячах программ. Пример кода:

Разберем этот небольшой код. За создание, собственно, окна, отвечает класс Tk(), и первым делом нужно создать экземпляр этого класса. Этот экземпляр принято называть root, хотя вы можете назвать его как угодно. Далее создаётся кнопка, при этом мы указываем её свойства (начинать нужно с указания окна, в примере — root). Здесь перечислены некоторые из них:

  • text — какой текст будет отображён на кнопке (в примере — ок)
  • width,height — соответственно, ширина и длина кнопки.
  • bg — цвет кнопки (сокращенно от background, в примере цвет — чёрный)
  • fg — цвет текста на кнопке (сокращённо от foreground, в примере цвет — красный)
  • font — шрифт и его размер (в примере — arial, размер — 14)

Далее, нашу кнопку необходимо разместить на окне. Для этого, в Tkinter используются специальные упаковщики( pack(), place(), grid() ). Поподробнее об упаковщиках узнаем позже. Пока, чтобы разместить несколько виджетов на окне, будем применять самый простой упаковщик pack(). В конце программы, нужно использовать функцию mainloop (см. пример), иначе окно не будет создано.

Label

Label — это виджет, предназначенный для отображения какой-либо надписи без возможности редактирования пользователем. Имеет те же свойства, что и перечисленные свойства кнопки.

Entry

Entry — это виджет, позволяющий пользователю ввести одну строку текста. Имеет дополнительное свойство bd (сокращённо от borderwidth), позволяющее регулировать ширину границы.

  • borderwidth — ширина бордюра элемента
  • bd — сокращение от borderwidth
  • width — задаёт длину элемента в знакоместах.
  • show — задает отображаемый символ.

Text — это виджет, который позволяет пользователю ввести любое количество текста. Имеет дополнительное свойство wrap, отвечающее за перенос (чтобы, например, переносить по словам, нужно использовать значение WORD).Например:

Методы insert, delete и get добавляют, удаляют или извлекают текcт. Первый аргумент — место вставки в виде ‘x.y’, где x – это строка, а y – столбец. Например:

Listbox

Listbox — это виджет, который представляет собой список, из элементов которого пользователь может выбирать один или несколько пунктов. Имеет дополнительное свойство selectmode, которое, при значении SINGLE, позволяет пользователю выбрать только один элемент списка, а при значении EXTENDED — любое количество. Пример:

Стоит заметить, что в этой библиотеке для того, чтобы использовать русские буквы в строках, нужно использовать Unicode-строки. В Python 2.x для этого нужно перед строкой поставить букву u, в Python 3.x этого делать вообще не требуется, т.к. все строки в нем изначально Unicode. Кроме того в первой или второй строке файла необходимо указать кодировку файла (в комментарии): coding: utf-8. Чаще всего используется формат в стиле текстового редактора emacs:

В Python 3.x кодировку файла можно не указывать, в этом случае по умолчанию предполагается utf-8.

Frame

Виджет Frame (рамка) предназначен для организации виджетов внутри окна. Рассмотрим пример:

Свойство bd отвечает за толщину края рамки.

Checkbutton

Checkbutton — это виджет, который позволяет отметить „галочкой“ определенный пункт в окне. При использовании нескольких пунктов нужно каждому присвоить свою переменную. Разберем пример:

IntVar() — специальный класс библиотеки для работы с целыми числами. variable — свойство, отвечающее за прикрепление к виджету переменной. onvalue, offvalue — свойства, которые присваивают прикреплённой к виджету переменной значение, которое зависит от состояния(onvalue — при выбранном пункте, offvalue — при невыбранном пункте).

Radiobutton

Виджет Radiobutton выполняет функцию, схожую с функцией виджета Checkbutton. Разница в том, что в виджете Radiobutton пользователь может выбрать лишь один из пунктов. Реализация этого виджета несколько иная, чем виджета Checkbutton:

В этом виджете используется уже одна переменная. В зависимости от того, какой пункт выбран, она меняет своё значение. Самое интересное, что если присвоить этой переменной какое-либо значение, поменяется и выбранный виджет. На этом мы прервём изучение типов виджетов (потом мы к ним обязательно вернёмся).

Scale

Scale (шкала) — это виджет, позволяющий выбрать какое-либо значение из заданного диапазона. Свойства:

  • orient — как расположена шкала на окне. Возможные значения: HORIZONTAL, VERTICAL (горизонтально, вертикально).
  • length — длина шкалы.
  • from_ — с какого значения начинается шкала.
  • to — каким значением заканчивается шкала.
  • tickinterval — интервал, через который отображаются метки шкалы.
  • resolution — шаг передвижения (минимальная длина, на которую можно передвинуть движок)

Здесь используется специальный метод get(), который позволяет снять с виджета определенное значение, и используется не только в Scale.

Scrollbar

Этот виджет даёт возможность пользователю «прокрутить» другой виджет (например текстовое поле) и часто бывает полезен. Использование этого виджета достаточно нетривиально. Необходимо сделать две привязки: command полосы прокрутки привязываем к методу xview/yview виджета, а xscrollcommand/yscrollcommand виджета привязываем к методу set полосы прокрутки.

Рассмотрим на примере:

Упаковщики

Упаковщик (менеджер геометрии, менеджер расположения) это специальный механизм, который размещает (упаковывает) виджеты на окне. В Tkinter есть три упаковщика: pack, place, grid. Обратите внимание, что в одном виджете можно использовать только один тип упаковки, при смешивании разных типов упаковки программа, скорее всего, не будет работать.

Разберем каждый из них по порядку:

pack() [6]

Упаковщик pack() является самым интеллектуальным (и самым непредсказуемым). При использовании этого упаковщика с помощью свойства side нужно указать к какой стороне родительского виджета он должен примыкать. Как правило этот упаковщик используют для размещения виджетов друг за другом (слева направо или сверху вниз). Пример:

Результат работы можно увидеть на скриншоте справа.

Для создания сложной структуры с использованием этого упаковщика обычно используют Frame, вложенные друг в друга.

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

  • side («left»/»right»/»top»/»bottom») — к какой стороне должен примыкать размещаемый виджет.
  • fill (None/»x»/»y»/»both») — необходимо ли расширять пространство предоставляемое виджету.
  • expand (True/False) — необходимо ли расширять сам виджет, чтобы он занял всё предоставляемое ему пространство.
  • in_ — явное указание в какой родительский виджет должен быть помещён.

Кроме основной функции у виджетов есть дополнительные методы для работы с упаковщиками.

  • pack_configure — синоним для pack.
  • pack_slaves (синоним slaves) — возвращает список всех дочерних упакованных виджетов.
  • pack_info — возвращает информацию о конфигурации упаковки.
  • pack_propagate (синоним propagate) (True/False) — включает/отключает распространении информации о геометрии дочерних виджетов. По умолчанию виджет изменяет свой размер в соответствии с размером своих потомков. Этот метод может отключить такое поведение (pack_propagate(False)). Это может быть полезно, если необходимо, чтобы виджет имел фиксированный размер и не изменял его по прихоти потомков. [7]
  • pack_forget (синоним forget) — удаляет виджет и всю информацию о его расположении из упаковщика. Позднее этот виджет может быть снова размещён.

grid() [8]

Этот упаковщик представляет собой таблицу с ячейками, в которые помещаются виджеты.

  • row — номер строки, в который помещаем виджет.
  • rowspan — сколько строк занимает виджет
  • column — номер столбца, в который помещаем виджет.
  • columnspan — сколько столбцов занимает виджет.
  • padx / pady — размер внешней границы (бордюра) по горизонтали и вертикали.
  • ipadx / ipady — размер внутренней границы (бордюра) по горизонтали и вертикали. Разница между pad и ipad в том, что при указании pad расширяется свободное пространство, а при ipad расширяется помещаемый виджет.
  • sticky («n», «s», «e», «w» или их комбинация) — указывает к какой границе «приклеивать» виджет. Позволяет расширять виджет в указанном направлении. Границы названы в соответствии со сторонами света. «n» (север) — верхняя граница, «s» (юг) — нижняя, «w» (запад) — левая, «e» (восток) — правая.
  • in_ — явное указание в какой родительский виджет должен быть помещён.

Для каждого виджета указываем, в какой он находится строке, и в каком столбце. Если нужно, указываем, сколько ячеек он занимает (если, например, нам нужно разместить три виджета под одним, необходимо «растянуть» верхний на три ячейки). Пример:

  • grid_configure — синоним для grid.
  • grid_slaves (синоним slaves) — см. pack_slaves.
  • grid_info — см. pack_info.
  • grid_propagate (синоним propagate) — см. pack_propagate.
  • grid_forget (синоним forget) — см. pack_forget.
  • grid_remove — удаляет виджет из-под управления упаковщиком, но сохраняет информацию об упаковке. Этот метод удобно использовать для временного удаления виджета (см. пример в описании метода destroy).
  • grid_bbox (синоним bbox) — возвращает координаты (в пикселях) указанных столбцов и строк. [9]
  • grid_location (синоним location) — принимает два аргумента: x и y (в пикселях). Возвращает номер строки и столбца в которые попадают указанные координаты, либо -1 если координаты попали вне виджета.
  • grid_size (синоним size) — возвращает размер таблицы в строках и столбцах.
  • grid_columnconfigure (синоним columnconfigure) и grid_rowconfigure (синоним rowconfigure) — важные функции для конфигурирования упаковщика. Методы принимают номер строки/столбца и аргументы конфигурации. Список возможных аргументов:
    • minsize — минимальная ширина/высота строки/столбца.
    • weight — «вес» строки/столбца при увеличении размера виджета. 0 означает, что строка/столбец не будет расширяться. Строка/столбец с «весом» равным 2 будет расширяться вдвое быстрее, чем с весом 1.
    • uniform — объединение строк/столбцов в группы. Строки/столбцы имеющие одинаковый параметр uniform будут расширяться строго в соответствии со своим весом.
    • pad — размер бордюра. Указывает, сколько пространства будет добавлено к самому большому виджету в строке/столбце.

    Пример, текстовый виджет с двумя полосами прокрутки:

    place() [10]

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

    Этот упаковщик, хоть и кажется неудобным, предоставляет полную свободу в размещении виджетов на окне.

    • anchor («n», «s», «e», «w», «ne», «nw», «se», «sw» или «center») — какой угол или сторона размещаемого виджета будет указана в аргументах x/y/relx/rely. По умолчанию «nw» — левый верхний
    • bordermode («inside», «outside», «ignore») — определяет в какой степени будут учитываться границы при размещении виджета.
    • in_ — явное указание в какой родительский виджет должен быть помещён.
    • x и y — абсолютные координаты (в пикселях) размещения виджета.
    • width и height — абсолютные ширина и высота виджета.
    • relx и rely — относительные координаты (от 0.0 до 1.0) размещения виджета.
    • relwidth и relheight — относительные ширина и высота виджета.

    Относительные и абсолютные координаты (а также ширину и высоту) можно комбинировать. Так например, relx=0.5, x=-2 означает размещение виджета в двух пикселях слева от центра родительского виджета, relheight=1.0, height=-2 — высота виджета на два пикселя меньше высоты родительского виджета.

    place_slaves, place_forget, place_info — см. описание аналогичных методов упаковщика pack.

    Привязка событий

    «Всё это хорошо» — наверное, подумали вы. — «Но как сделать так, чтобы мои виджеты что-то делали, а не просто красовались на окне?».

    command

    Для большинства виджетов, реагирующих на действие пользователя, активацию виджета (например нажатие кнопки) можно привязать с использованием опции command. К таким виджетам относятся: Button, Checkbutton, Radiobutton, Spinbox, Scrollbar, Scale. Выше мы уже неоднократно пользовались этим способом:

    Такой способ является предпочтительным и наиболее удобным способом привязки.

    Метод bind[1] привязывает событие к какому-либо действию (нажатие кнопки мыши, нажатие клавиши на клавиатуре и т.д.). bind принимает три аргумента:

    • название события
    • функцию, которая будет вызвана при наступлении события
    • третий аргумент (необязательный) — строка «+» — означает, что эта привязка добавляется к уже существующим. Если третий аргумент опущен или равен пустой строке — привязка замещает все другие привязки данного события к виджету.

    Метод bind возвращает идентификатор привязки, который может быть использован в функции unbind.

    Обратите внимание, что если bind привязан к окну верхнего уровня, то Tkinter будет обрабатывать события всех виджетов этого окна (см. также bind_all ниже).

    Функция, которая вызывается при наступлении события, должна принимать один аргумент. Это объект класса Event, в котором описано наступившее событие. Объект класса Event имеет следующие атрибуты (в скобках указаны события, для которых этот атрибут установлен):

    • serial — серийный номер события (все события)
    • num — номер кнопки мыши (ButtonPress, ButtonRelease)
    • focus — имеет ли окно фокус (Enter, Leave)
    • height и width — ширина и высота окна (Configure, Expose)
    • keycode — код нажатой клавиши (KeyPress, KeyRelease)
    • state — состояние события (для ButtonPress, ButtonRelease, Enter, KeyPress, КeyRelease, Leave, Motion — в виде числа; для Visibility — в виде строки)
    • time — время наступления события (все события)
    • x и y — координаты мыши
    • x_root и y_root — координаты мыши на экране (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
    • char — набранный на клавиатуре символ (KeyPress, KeyRelease)
    • send_event — см. документацию по X/Windows
    • keysym — набранный на клавиатуре символ (KeyPress, KeyRelease)
    • keysym_num — набранный на клавиатуре символ в виде числа (KeyPress, KeyRelease)
    • type — тип события в виде числа (все события)
    • widget — виджет, который получил событие (все события)
    • delta — изменение при вращении колеса мыши (MouseWheel)

    Эта функция может возвращать строки «continue» и «break». Если функция возвращает «continue» то Tkinter продолжит обработку других привязок этого события, если «break» — обработка этого события прекращается. Если функция ничего не возвращает (если возвращает None), то обработка событий продолжается (т.е. это эквивалентно возвращению «continue»).

    Есть три формы названия событий. Самый простой случай это символ ASCII. Так описываются события нажатия клавиш на клавиатуре:

    callback вызывается каждый раз, когда будет нажата клавиша «z».

    Второй способ длиннее, но позволяет описать больше событий. Он имеет следующий синтаксис:

    Название события заключено в угловые скобки. Внутри имеются ноль или более модификаторов, тип события и дополнительная информация (номер нажатой клавиши мыши или символ клавиатуры) Поля разделяются дефисом или пробелом. Пример (привязываем одновременное нажатие Ctrl+Shift+q):

    (в данном примере KeyPress можно убрать).

    Третий способ позволяет привязывать виртуальные события — события, которые генерируются самим приложением. Такие события можно создавать самим, а потом привязывать их. Имена таких событий помещаются в двойные угловые скобки: <<Paste>>. Есть некоторое количество уже определённых виртуальных событий.

    • Return — Enter
    • Escape — Esc
    • Control — Ctrl
    • Alt
    • Shift
    • Lock
    • Extended
    • Prior — PgUp
    • Next — PgDown
    • Button1, B1 — нажата первая (левая) кнопка мыши
    • Button2, B2 — вторая (средняя) кнопка мыши
    • Button3, B3 — третья (правая)
    • Button4, B4 — четвёртая
    • Button5, B5 — пятая
    • Mod1, M1, Command
    • Mod2, M2, Option
    • Mod3, M3
    • Mod4, M4
    • Mod5, M5
    • Meta, M
    • Double — двойной щелчок мыши (например, <Double-Button-1>)
    • Triple — тройной
    • Quadruple — четверной

    Здесь перечислены все возможные типы событий, для самых часто используемых дано описание. Более подробно см. man bind.

    • Activate, Deactivate
    • MouseWheel — прокрутка колесом мыши
    • KeyPress, KeyRelease — нажатие и отпускание клавиши на клавиатуре
    • ButtonPress, ButtonRelease, Motion — нажатие, отпускание клавиши мыши, движение мышью
    • Configure — изменение положения или размера окна
    • Map, Unmap — показывание или сокрытие окна (например, в случае сворачивания/разворачивания окна пользователем)
    • Visibility
    • Expose — событие генерируется, когда необходимо всё окно или его часть перерисовать
    • Destroy — закрытие окна
    • FocusIn, FocusOut — получение или лишение фокуса
    • Enter, Leave — Enter генерируется когда курсор мыши «входит» в окно, Leave — когда «уходит» из окна
    • Property
    • Colormap
    • MapRequest, CirculateRequest, ResizeRequest, ConfigureRequest, Create
    • Gravity, Reparent, Circulate

    <Button-1> или <1> — нажата левая клавиша мыши.

    <Alt-Motion> — движение мышью с нажатой на клавиатуре клавишей Alt.

    <Key> — нажатие любой клавиши на клавиатуре.

    • bind_all — создаёт привязку для всех виджетов приложения. Отличие от привязки к окну верхнего уровня заключается в том, что в случае привязки к окну привязываются все виджеты этого окна, а этот метод привязывает все виджеты приложения (у приложения может быть несколько окон).
    • bind_class — создаёт привязку для всех виджетов данного класса
    • bindtags — позволяет изменить порядок обработки привязок. По умолчанию порядок следующий: виджет, класс, окно, all; где виджет — привязка к виджету (bind), класс — привязка к классу (bind_class), окно — привязка к окну (root.bind), all — привязка всех виджетов (bind_all).

    Пример, меняем порядок обработки привязок на обратный:

    • unbind — отвязать виджет от события. В качестве аргумента принимает идентификатор, полученный от метода bind.
    • unbind_all — то же, что и unbind, только для метода bind_all.
    • unbind_class — то же, что и unbind, только для метода bind_class.

    Изображения

    Для работы с изображениями в Tkinter имеется два класса BitmapImage и PhotoImage. BitmapImage представляет собой простое двухцветное изображение, PhotoImage — полноцветное изображение.

    BitmapImage

    Конструктор класса принимает следующие аргументы:

    • background и foreground — цвета фона и переднего плана для изображения. Поскольку изображение двухцветное, то эти параметры определяют соответственно чёрный и белый цвет.
    • file и maskfile — пути к файлу с изображением и к маске (изображению, указывающему какие пиксели будут прозрачными).
    • data и maskdata — вместо пути к файлу можно указать уже загруженные в память данные изображения. Данная возможность удобна для встраивания изображения в программу.

    PhotoImage

    PhotoImage позволяет использовать полноцветное изображение. Кроме того у этого класса есть несколько (достаточно примитивных) методов для работы с изображениями. PhotoImage гарантированно понимает формат GIF.

    • file — путь к файлу с изображением.
    • data — вместо пути к файлу можно указать уже загруженные в память данные изображения. Изображения в формате GIF могут быть закодированы с использованием base64. Данная возможность удобна для встраивания изображения в программу.
    • format — явное указание формата изображения.
    • width, height — ширина и высота изображения.
    • gamma — коррекция гаммы.
    • palette — палитра изображения.

    ttk (themed tk) это расширение tcl/tk с новым набором виджетов. В ttk используется новый движок для создания виджетов. Этот движок обладает поддержкой тем и стилей оформления. Благодаря этому виджеты ttk выглядят более естественно в различных операционных системах.

    Начиная с версий python 2.7 и 3.1.2 в Tkinter включён модуль для работы с ttk.

    Внешний вид некоторых виджетов ttk, используется тема clam

    В ttk включены следующие виджеты, которые можно использовать вместо соответствующих виджетов tk: Button, Checkbutton, Entry, Frame, Label, LabelFrame, Menubutton, PanedWindow, Radiobutton, Scale и Scrollbar. Кроме того имеется несколько новых виджетов: Combobox, Notebook, Progressbar, Separator, Sizegrip и Treeview.

    Поскольку это относительно новая возможность Tkinter, несколько слов об установке этого модуля. Версии python 2.7/3.1.2 и старше уже имеют в своём составе этот модуль. Для использования ttk с более ранними версиями python, его нужно установить самостоятельно. Домашняя страница модуля. В данный момент python-ttk хостится в svn python.org. Модуль представляет собой один файл — ttk.py, который нужно положить в каталог, где его сможет найти python. Прямые ссылки для скачивания: для версии 2.x, для версии 3.x.

    С точки зрения программиста главное отличие новых виджетов от старых заключается в том, что у виджетов ttk отсутствуют опции для конфигурирования его внешнего вида. Сравните, например, количество STANDARD OPTIONS для старого и нового виджета button. Конфигурация внешнего вида виджетов ttk осуществляется через темы и стили. В остальном использование виджетов ttk аналогично соответствующим виджетам tk.

    ttk имеет четыре встроенных темы: default, classic, alt, clam. Кроме того дополнительно под Windows есть темы winnative, xpnative и vista, а под Mac OS X — aqua.

    Style

    Style это класс для работы со стилями и темами. Именно этот класс надо использовать для конфигурирования внешнего вида виджетов. Основные методы класса:

    Конфигурирование внешнего вида виджетов. В качестве аргументов принимает название стиля виджета (например «TButton») и список опций конфигурирования. Пример:

    Конфигурирование внешнего вида виджетов в зависимости от их состояний (active, pressed, disabled и т.д.). В качестве аргументов принимает название стиля виджета и список опций конфигурирования, где опции представлены в виде списка. Пример:

    Возвращает соответствующую опцию конфигурирования. Пример:

    Изменяет layout (схему) виджета. Виджеты ttk состоят из отдельных элементов, опций конфигурирования и других вложенных layouts. Следующий пример иллюстрирует применение метода layout:

    Создаёт новый элемент темы.

    Возвращает список элементов текущей темы.

    Возвращает список опций (конфигурацию), указанного в аргументе элемента.

    Создаёт новую тему. Аргументы те же, что и в theme_settings.

    Конфигурирует существующую тему. Первый аргумент — название темы, второй аргумент — словарь, ключами которого являются названия стилей (TButton и т.п.), а значениями — layout соответствующего стиля.

    Возвращает список доступных тем.

    Изменяет текущую тему на указанную в аргументе.

    Combobox

    Виджет Combobox предназначен для отображения списка значений, их выбора или изменения пользователем. В версии tk ему подобен виджет Listbox. Разница заключается в том, что Combobox имеет возможность сворачиваться подобно свитку, а Listbox будет отображаться всегда открытым. Что бы отобразить Combobox с заранее заданными значениями в форме, достаточно сделать следующее:

    Progressbar

    Виджет отображает уровень загрузки.

    • length — длина полосы.

    Запускает бесконечный цикл загрузки. Шаг длиною 1 выполняется один раз в указанное время (в миллисекундах).

    Tkinter MainLoop Function – Understanding how it Works

    report this ad report this ad report this ad

    In this Python Tkinter Tutorial, we will discuss the usage and inner workings behind the “mainloop” function.

    We use this function on our Tkinter window, typically called “root”, in every single Tkinter program. But often the actual working and purpose of this function is forgotten. This tutorial aims to explain this, so you have a better idea of what’s going on behind the scenes.

    Understanding Tkinter MainLoop

    If you remember correctly, the mainloop function is called as shown below. And until it is called, the Tkinter window will not appear.

    Think about how code is executed for a moment. Normally, your programs will begin executing and finish within a fraction of a second. But this does not happened with games or GUI windows, which last indefinetly. Have you ever wondered why?

    This is because they must run infinitely, until they are ordered to be closed, either by the program or by a manual action by the user. So how is this possible? With Loops of course. With the right condition, a loop can run indefinitely, repeating the same chunk of code over and over again.

    Event Loop

    If we take a deeper look into this, there are several more elements to it. There is what we call an “event loop” (within the infinite loop) that “listens” for certain actions that the user may take (such as clicking a button). Once an event has been detected, a corresponding action is taken (such as closing the window when the quite button is pressed)

    Without an event loop, GUI windows would remain static, and unable to change or be interactive like they normally are. You may not realize it, but Tkinter has one of these too.

    If you want to visualize the Tkinter MainLoop function a bit, the below code should give you a little idea.

    Game Loop in Pygame

    In order to better understand the Tkinter MainLoop() function, let’s take a look at another popular Python Library called Pygame.

    Pygame is a game library used to create simple 2D games in Python. And as I said earlier, games also run infinitely, hence the also need an infinite loop, commonly referred to as the game loop.

    One big difference between Tkinter and Pygame, is that you have to make your own (infinite) Game loop in Pygame. This actually helps build up your understanding alot, and makes things much more flexible and under your control.

    Shown below is the code for a Game Loop in Pygame. You don’t need to focus on the syntax much, rather just o the concept.

    1. There is an infinite while loop, that only breaks once the QUIT event is detected.
    2. Within the While loop, there is a for loop that we call the event loop. (Implementation will vary from library to library, but all have an event loop that continuously listens for events, and then acts accordingly)
    3. Update function is being called on all entities in every iteration of the loop.
    4. All entities are re-drawn to the screen in every iteration of the loop.

    These features can be said to be very similar to those found within the Tkinter mainloop. Hence it should serve as a good reference.

    This marks the end of the Python Tkinter MainLoop Function Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

    Что такое mainloop в python

    In this Python Tkinter tutorial, we will learn everything about Python Tkinter Mainloop. Also, we will cover these topics.

    1. Python Tkinter Mainloop
    2. Python Tkinter Mainloop Thread
    3. Python Tkinter Mainloop exit
    4. Python Tkinter Mainloop Blocking
    5. Python Tkinter Mainloop Non Blocking
    6. Python Tkinter Mainloop Update
    7. Python Tkinter Mainloop Event
    8. Python Tkinter Mainloop Timer
    9. Python Tkinter Mainloop Background

    Python Tkinter Mainloop

    Mainloop in Python Tkinter is an infinite loop of the application window which runs forever so that we can see the still screen.

    • The application window is like a frame that keeps on destroying every microsecond but the main loop keeps on creating a new updated window.
    • This process of destroying old window screens and creating a new one happens so fast that human eyes don’t even realize it.
    • Since the process runs infinite time that is why we are able to see the application in front of us and when we close the window then the loop terminates or exits.
    • C or C++ programmers can relate this with a situation when we run a program in C or C++ the black output window closes after showing the result. But if intentionally or accidentally the infinite loop is triggered then the black window stays and keeps on displaying the message.
    • Infinite loop projects the updated window and the process is too fast that we feel like it is updating.

    Here is the code to implement the mainloop in Python Tkinter. mainloop() is always applied at the last line of the code.

    python tkinter mainloop

    Python Tkinter Mainloop Thread

    Thread is the process that goes parallel with the program as a separate entity. In other words, by using thread we can run multiple things in the same program at the same time.

    • Thread is like a branch of a program that runs as a separate entity and it merges back to the mainloop once the task is complete.
    • Thread saves users time by avoiding screen freezing while one task is running.

    Python Tkinter Mainloop exit

    Python Tkinter provides destroy() function using which we can exit the mainloop in Python Tkinter. destroy() function can be applied on parent window, frames, canvas, etc.

    Here is the code to demonstrate Python Tkinter Mainloop Exit

    In this code, we have created an Exit button that will close the window when clicked.

    Here is the output of the above code to demonstrate Python Tkinter Mainloop Exit

    In this output, mainloop exits when the exit button is clicked.

    python tkinter mainloop exit

    Python Tkinter Mainloop Blocking

    The Mainloop() method plays a major role in Python Tkinter as it updates the Graphical User Interface(GUI) of the application every time an event occurs.

    • But the sad part in the above statement is mainloop waits for an event to occur. This means it is blocking the code that is outside the mainloop.
    • Python executes the code line by line so until and unless the mainloop is not terminated it does not allow python to execute code outside the mainloop.
    • In the next section, we have learned how to fix the mainloop blocking in Python Tkinter.

    Here is the code to demonstrate the Python Tkinter Mainloop Blocking

    In this code, we have created GUI (Tkinter) and terminal based application.

    Output:

    • In this output, you can notice that when app.py is executed then the Tkinter application appeared on the screen but the terminal-based application appeared only when the Tkinter application is closed.
    • It happened because mainloop was blocking the code.

    Python Tkinter Mainloop Non Blocking

    In the previous section, we have seen Python Tkinter Mainloop Blocking. Now we will learn how to create a Python Tkinter Mainloop Non Blocking.

    • Threading is the library in Python Tkinter using which mainloop non-blocking code can be written.
    • Threading promotes multitasking features in the program. This means the block of code runs as an individual entity.
    • Use of threading is preferred in the big applications but for small applications after() and update() did the same thing.
    • In our example, we will be explaining using after(). for Threading and update() we have different sections in this blog.
    • So if we continue the previous example, now the GUI (Tkinter) and Terminal-based applications should appear at the same time.

    Here is the code to demonstrate the Python Tkinter Mainloop Non Blocking

    In this code, we have created function that holds the code for terminal based application and this function is called using after function on line 18.

    In this output, both terminal-based and GUI-based applications are running simultaneously. In this way, the mainloop is non-blocking the other applications.

    Python Tkinter Mainloop Update

    Update() method in mainloop in Python Tkinter is used to show the updated screen. It reflects the changes when an event occurs. In the below example we have demonstrated update() function in Python Tkinter.

    Source code of Python Tkinter Mainloop Update Example

    In this code, date, day and time is being displayed. This information is fetched from the system and the Tkinter window keeps on updating to display latest information.

    Output of Python Tkinter Mainloop Update Example

    In this output, Time is keep on changing and the updates are visible because we have applied update function on main window.

    python tkinter mainloop update

    Python Tkinter Mainloop Event

    In this section, we will learn about event in mainloop in Python Tkinter. Also, we see an example for the same.

    • An event refers to any activity performed it could be scheduled activity or manually performed by the user. Click of a button, filling the information in the Entry box, selecting radio buttons, etc triggers an event.
    • Mainloop waits for an event to occur so that it could update the screen. This wait for an event causes blocking but it can be resolved by using thread, update, or after functions in Python Tkinter
    • In our example, we will demonstrate the program that will generate a password and at the same time, it will display a message on the terminal.

    Source code of Python Tkinter Mainloop Event Example

    In this code, we have created 2 programs, one is gui-based and other is terminal-based. Out of these Terminal based triggers an event in every 2 seconds where as gui based application triggers when user clicks on the button. The thing to notice here is both are running parallel with out blocking the code.

    Output for Python Tkinter Mainloop Event example

    In this output, two events are occurring but mainloop is not blocking the code. You can see both Gui based and terminal based applications are running parallel.

    Python Tkinter Mainloop Timer

    Mainloop plays an important role in Python Tkinter as it displays updated information on the screen.

    • Timer is a time-related program that we can create using Mainloop in Python Tkinter.
    • We have a dedicated section in which we have created Countdown Timer using Python Tkinter

    Python Tkinter Mainloop Background

    In this section, we will learn how to run an application in the background using the mainloop in Python Tkinter.

    • We will use the example in Python Tkinter Mainloop Update to explain the Python Tkinter Mainloop background.
    • In Python Tkinter Mainloop Update we have displayed the date, day, and time. Out of these only time is updating constantly whereas date and day are running in the background.

    You may like the following Python tkinter tutorials:

    In this tutorial, we will learn everything about Python Tkinter Mainloop. Also, we will cover these topics.

    • Python Tkinter Mainloop
    • Python Tkinter Mainloop Thread
    • Python Tkinter Mainloop exit
    • Python Tkinter Mainloop Non Blocking
    • Python Tkinter Mainloop Blocking
    • Python Tkinter Mainloop Update
    • Python Tkinter Mainloop Event
    • Python Tkinter Mainloop Timer
    • Python Tkinter Mainloop Background

    Bijay Kumar MVP

    Entrepreneur, Founder, Author, Blogger, Trainer, and more. Check out my profile.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *