Tkinter mainloop

Tkinter is defined as a module inside the Python standard library that helps to serve as an interface to an easy Toolkit Tk. This has a variety of GUI to build an interface like buttons and widgets. The method mainloop plays a vital role in Tkinter as it is a core application that waits for events and helps in updating the GUI or in simple terms, we can say it is event-driven programming. If no mainloop() is used then nothing will appear on the window Screen. This method takes all the objects that were created and have interactions response.
ADVERTISEMENT
Popular Course in this category
TKINTER Course Bundle — 2 Courses in 1 | 3 Mock Tests
Web development, programming languages, Software testing & others
Syntax
To get started
from tkinter import Tk // Tkinter Library root = Tk() //Creates root master with the TK() constructor app = App(root) app.pack() root.mainloop //main event loop.
How the mainloop work in Tkinter?
Root. mainloop() is simply a method in the main window that executes what we wish to execute in an application (lets Tkinter to start running the application). As the name implies it will loop forever until the user exits the window or waits for any events from the user. The mainloop automatically receives events from the window system and deliver them to the application widgets. This gets quit when we click on the close button of the title bar. So, any code after this mainloop() method will not run.
When a GUI is gets started with the mainloop() a method call, Tkinter python automatically initiates an infinite loop named as an event loop. So, after this article, we will be able to use all the widgets to develop an application in Python. Different widgets are Combo box, button, label, Check button, Message Box, Images, and Icons.
Constructor
Well, a root window is created by calling Tkinter Constructor TK() as it creates a widget.
Root=tk.TK() // Constructor
This line of code automatically creates a GUI window with a title bar, close button.
Creating window TK() Window =TK() ……… Window.mainloop()
Methods
Tkinter provides the following methods to specify a widget to display on a window.
pack(): This method helps in Placing the widgets within its master. With options like side, fill, expand.
Widget.pack();
grid(): This method helps to place a widget in a grid format or tabular form. We can specify in the method call with the number of rows and columns. It takes possible options like column, row, ipadx, and Y and sticky.
Widget.grid();
Place(): This method arranges the widgets by placing them in specific positions instructed by the programmer. It organizes with respective to X and Y coordinates.
Widget.place();
Grid Sample code
rom tkinter import * master = Tk() Label(master, text='Full Name').grid(row=1) Label(master, text='Email-ID').grid(row=2) A = Entry(master) B = Entry(master) A.grid(row=1, column=2) B.grid(row=2, column=1) mainloop()
Examples
Here are the following examples mention below
Example #1
Code:
import tkinter as tk res = tk.Tk() res.title('Incrementing the Process') button = tk.Button(res, text='Pause', width=30, command=res.destroy) button.pack() res.mainloop()
Explanation:
The above code is a simple application that creates a button widget, when we click on it we could see a tiny pop-up window with the text ‘Pause’. The output is shown in the below screenshot.
Output:

Example #2
Using pack() method
Code:
import tkinter from tkinter import * parent = Tk() blbtn= Button(parent, text = "Blue", fg = "Blue") blbtn.pack( side = TOP) Brbtn = Button(parent, text = "Brown", fg = "Brown") Brbtn.pack( side = LEFT) Aqbtn = Button(parent, text = "Aqua", fg = "Aqua") Aqbtn .pack( side = BOTTOM ) orgbtn = Button(parent, text = "Orange", fg = "Orange") orgbtn.pack( side = RIGHT) parent.mainloop()
Explanation:
Here pack() method is used to organize the button in a good format. It specifies the side of a parent to place on a window.
Output:

Example #3
Using Label widgets on the GUI window.
Code:
import tkinter as tk window = tk.Tk() frame = tk.Frame(master=window, width=100, height=100) frame.pack() lab1 = tk.Label(master=frame, text="Points at (5, 5)", bg="Aqua") lab1.place(x=5, y=5) lab2 = tk.Label(master=frame, text="Points at (65, 65)", bg="Pink") lab2.place(x=65, y=65) window.mainloop()
Explanation:
Here the code produces a window like this. We have imported a Tkinter package and a window is defined. Next, a label is defined to show the output with the points on the window. The scale point is given for each label. Finally, the mainloop is executed to touch the event.
Output:

Example #4
Using Check box -mainloop() is executed
Code:
from tkinter import * root = Tk() root.geometry("400x300") aa = Label(root, text ='EDUCBA-Online ', font = "60") aa.pack() Chckbtn1 = IntVar() Chckbtn2 = IntVar() Chckbtn3 = IntVar() Btn1 = Checkbutton(root, text = "Courses", variable = Chckbtn1, onvalue = 2, offvalue = 0, height = 3, width = 12)Btn2 = Checkbutton(root, text = "Free-Trial", variable = Chckbtn2, onvalue = 3, offvalue = 0, height = 3, width = 12)Btn3 = Checkbutton(root, text = "Paid", variable = Chckbtn3, onvalue = 1, offvalue = 0, height = 2, width = 10)Btn1.pack() Btn2.pack() Btn3.pack() mainloop()
Explanation:
When we execute the above code, we could see a window pop-up with a title and some label and button clicks. We have used a Class Tk to create the main window and a pack() method is used to position inside the parent window. And the command keyword is used here to specify the function in handling the click events and here it is a check box.
Output:

Example #5
Code:
import tkinter as tk window = tk.Tk() frA = tk.Frame() labA = tk.Label(master=frA, text="This is A Frame") labA.pack() frb = tk.Frame() labB = tk.Label(master=frb, text="This is B Frame") labB.pack() frb.pack() frA.pack() window.mainloop()
Output:

Example #6
Message box-Pop up
Code:
import tkinter import tkinter.messagebox import datetimedef displaydate():now = datetime.datetime.now() disp = 'Today date is: <>'.format(now) tkinter.messagebox.showinfo("Information", disp)root = tkinter.Tk() root.title('Pop up MessageBox') butn = tkinter.Button(root, text="Display Dat", padx=7, pady=7, width=12, command=displaydate) butn.pack(pady=11) root.geometry('400x400+400+350') root.mainloop()
Explanation:
The above code shows the information on the message box. The message is displayed when we click on the display date button to show the current date and time as well.
Output:

Example #7
Using place() method
Code:
from tkinter import * top = Tk() top.geometry("300x150") LoginID = Label(top, text = "LoginID").place(x = 20,y = 40) email = Label(top, text = "Email").place(x = 20, y = 80) Phone = Label(top, text = "Phone").place(x = 20, y = 110) a1 = Entry(top).place(x = 70, y = 40) a2 = Entry(top).place(x = 70, y = 80) a3 = Entry(top).place(x = 85, y = 110) top.mainloop()
Output:

Conclusion – Tkinter mainloop
Tkinter being an open-source GUI available in python has made a popular toolkit for User Interface Design. So, therefore, in this article, we have seen simple programming examples with simplicity to show how the mainloop works and different methods used to build a widget. This mainloop helps to respond to events like a mouse and keyboard events.
Recommended Articles
This is a guide to Tkinter mainloop. Here we discuss How the mainloop works in Tkinter and Examples along with the codes and outputs. You may also have a look at the following articles to learn more –
- Tkinter PhotoImage
- Tkinter Colors
- Tkinter Grid
- Tkinter Scrollbar
ADVERTISEMENT
MICROSOFT POWER BI Course Bundle — 8 Courses in 1
34+ Hours of HD Videos
8 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5
ADVERTISEMENT
CYBER SECURITY & ETHICAL HACKING Course Bundle — 13 Courses in 1 | 3 Mock Tests
64+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
ADVERTISEMENT
MICROSOFT AZURE Course Bundle — 15 Courses in 1 | 12 Mock Tests
63+ Hour of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
ADVERTISEMENT
KALI LINUX Course Bundle — 6 Courses in 1
20+ Hours of HD Videos
6 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5
Primary Sidebar
All in One Software Development Bundle 5000+ Hours of HD Videos | 149 Learning Paths | 1050+ Courses | Verifiable Certificate of Completion | Lifetime Access
Financial Analyst Masters Training Program 2000+ Hours of HD Videos | 43 Learning Paths | 550+ Courses | Verifiable Certificate of Completion | Lifetime Access
Tkinter understanding mainloop
Till now, I used to end my Tkinter programs with: tk.mainloop() , or nothing would show up! See example:
from Tkinter import * import random import time tk = Tk() tk.title = "Game" tk.resizable(0,0) tk.wm_attributes("-topmost", 1) canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0) canvas.pack() class Ball: def __init__(self, canvas, color): self.canvas = canvas self.id = canvas.create_oval(10, 10, 25, 25, fill=color) self.canvas.move(self.id, 245, 100) def draw(self): pass ball = Ball(canvas, "red") tk.mainloop()
However, when tried the next step in this program (making the ball move by time), the book am reading from, says to do the following. So I changed the draw function to:
def draw(self): self.canvas.move(self.id, 0, -1)
and add the following code to my program:
while 1: ball.draw() tk.update_idletasks() tk.update() time.sleep(0.01)
But I noticed that adding this block of code, made the use of tk.mainloop() useless, since everything would show up even without it. At this moment I should mention that my book never talks about tk.mainloop() (maybe because it uses Python 3) but I learned about it searching the web since my programs didn’t work by copying book’s code! So I tried doing the following that would not work.
while 1: ball.draw() tk.mainloop() time.sleep(0.01)
What’s going on? What does tk.mainloop() ? What does tk.update_idletasks() and tk.update() do and how that differs from tk.mainloop() ? Should I use the above loop? tk.mainloop() ? or both in my programs?
1 1 1 silver badge
asked Mar 20, 2015 at 2:09
1,513 2 2 gold badges 18 18 silver badges 23 23 bronze badges
About mainloop: stackoverflow.com/questions/8683217/…
Mar 20, 2015 at 2:34
these question are connected somehow. i don’t think it would be nice making 3 questions in 3 topics that talk almost about the same thing. 😐
Mar 20, 2015 at 2:34
I suggest getting a different book.
Aug 2, 2022 at 17:29
Working links: Here you have something about the update function. Here about update_idletasks ..
Aug 2, 2022 at 17:41
3 Answers 3
tk.mainloop() blocks. It means that execution of your Python commands halts there. You can see that by writing:
while 1: ball.draw() tk.mainloop() print("hello") #NEW CODE time.sleep(0.01)
You will never see the output from the print statement. Because there is no loop, the ball doesn’t move.
On the other hand, the methods update_idletasks() and update() here:
while True: ball.draw() tk.update_idletasks() tk.update()
. do not block; after those methods finish, execution will continue, so the while loop will execute over and over, which makes the ball move.
An infinite loop containing the method calls update_idletasks() and update() can act as a substitute for calling tk.mainloop() . Note that the whole while loop can be said to block just like tk.mainloop() because nothing after the while loop will execute.
However, tk.mainloop() is not a substitute for just the lines:
tk.update_idletasks() tk.update()
Rather, tk.mainloop() is a substitute for the whole while loop:
while True: tk.update_idletasks() tk.update()
Response to comment:
Here is what the tcl docs say:
Update idletasks
This subcommand of update flushes all currently-scheduled idle events from Tcl’s event queue. Idle events are used to postpone processing until “there is nothing else to do”, with the typical use case for them being Tk’s redrawing and geometry recalculations. By postponing these until Tk is idle, expensive redraw operations are not done until everything from a cluster of events (e.g., button release, change of current window, etc.) are processed at the script level. This makes Tk seem much faster, but if you’re in the middle of doing some long running processing, it can also mean that no idle events are processed for a long time. By calling update idletasks, redraws due to internal changes of state are processed immediately. (Redraws due to system events, e.g., being deiconified by the user, need a full update to be processed.)
APN As described in Update considered harmful, use of update to handle redraws not handled by update idletasks has many issues. Joe English in a comp.lang.tcl posting describes an alternative:
So update_idletasks() causes some subset of events to be processed that update() causes to be processed.
- Keeping the GUI alive while some long-running calculation is executing. See Countdown program for an alternative. 2) Waiting for a window to be configured before doing things like geometry management on it. The alternative is to bind on events such as that notify the process of a window’s geometry. See Centering a window for an alternative.
Is there any chance I can make my program work without the while loop?
Yes, but things get a little tricky. You might think something like the following would work:
class Ball: def __init__(self, canvas, color): self.canvas = canvas self.id = canvas.create_oval(10, 10, 25, 25, fill=color) self.canvas.move(self.id, 245, 100) def draw(self): while True: self.canvas.move(self.id, 0, -1) ball = Ball(canvas, "red") ball.draw() tk.mainloop()
The problem is that ball.draw() will cause execution to enter an infinite loop in the draw() method, so tk.mainloop() will never execute, and your widgets will never display. In gui programming, infinite loops have to be avoided at all costs in order to keep the widgets responsive to user input, e.g. mouse clicks.
So, the question is: how do you execute something over and over again without actually creating an infinite loop? Tkinter has an answer for that problem: a widget’s after() method:
from Tkinter import * import random import time tk = Tk() tk.title = "Game" tk.resizable(0,0) tk.wm_attributes("-topmost", 1) canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0) canvas.pack() class Ball: def __init__(self, canvas, color): self.canvas = canvas self.id = canvas.create_oval(10, 10, 25, 25, fill=color) self.canvas.move(self.id, 245, 100) def draw(self): self.canvas.move(self.id, 0, -1) self.canvas.after(1, self.draw) #(time_delay, method_to_execute) ball = Ball(canvas, "red") ball.draw() #Changed per Bryan Oakley's comment tk.mainloop()
The after() method doesn’t block (it actually creates another thread of execution), so execution continues on in your python program after after() is called, which means tk.mainloop() executes next, so your widgets get configured and displayed. The after() method also allows your widgets to remain responsive to other user input. Try running the following program, and then click your mouse on different spots on the canvas:
from Tkinter import * import random import time root = Tk() root.title = "Game" root.resizable(0,0) root.wm_attributes("-topmost", 1) canvas = Canvas(root, width=500, height=400, bd=0, highlightthickness=0) canvas.pack() class Ball: def __init__(self, canvas, color): self.canvas = canvas self.id = canvas.create_oval(10, 10, 25, 25, fill=color) self.canvas.move(self.id, 245, 100) self.canvas.bind("", self.canvas_onclick) self.text_id = self.canvas.create_text(300, 200, anchor='se') self.canvas.itemconfig(self.text_id, text='hello') def canvas_onclick(self, event): self.canvas.itemconfig( self.text_id, text="You clicked at (<>, <>)".format(event.x, event.y) ) def draw(self): self.canvas.move(self.id, 0, -1) self.canvas.after(50, self.draw) ball = Ball(canvas, "red") ball.draw() #Changed per Bryan Oakley's comment. root.mainloop()
Введение в Tkinter

Tkinter – это кроссплатформенная библиотека для разработки графического интерфейса на языке Python (начиная с Python 3.0 переименована в tkinter). Tkinter расшифровывается как Tk interface, и является интерфейсом к Tcl/Tk.
Tkinter входит в стандартный дистрибутив Python.
Весь код в этой статье написан для Python 2.x.
Чтобы убедиться, что Tkinter установлен и работает, воспользуемся стандартной функцией Tkinter _test():
import Tkinter Tkinter._test()
После выполнения данного кода должно появиться следующее окно:

Отлично, теперь можно приступать к написанию нескольких простых программ для демонстрации основных принципов Tkinter.
Hello world
Конечно, куда же без него. Первым делом нам нужно создать главное окно, написав
from Tkinter import * root = Tk()
Да-да, всего одна строка, это вам не WinAPI (=. Теперь создадим кнопку, при нажатии на которую будет выводиться текст в консоль:
def Hello(event): print "Yet another hello world" btn = Button(root, #родительское окно text="Click me", #надпись на кнопке width=30,height=5, #ширина и высота bg="white",fg="black") #цвет фона и надписи btn.bind("", Hello) #при нажатии ЛКМ на кнопку вызывается функция Hello btn.pack() #расположить кнопку на главном окне root.mainloop()
Всё просто, не так ли? Создаём экземпляр класса Button, указываем родителя и при желании список параметров. Есть еще немало параметров, таких как шрифт, толщина рамки и т.д.
Затем привязываем к нажатию на кнопку событие (можно привязать несколько разных событий в зависимости, например, от того, какой кнопкой мыши был нажат наш btn.
mainloop() запускает цикл обработки событий; пока мы не вызовем эту функцию, наше окно не будет реагировать на внешние раздражители.
Упаковщики
Функция pack() — это так называемый упаковщик, или менеджер расположения. Он отвечает за то, как виджеты будут располагаться на главном окне. Для каждого виджета нужно вызвать метод упаковщика, иначе он не будет отображён. Всего упаковщиков три:
pack(). Автоматически размещает виджеты в родительском окне. Имеет параметры side, fill, expand. Пример:
from Tkinter import * root = Tk() Button(root, text = '1').pack(side = 'left') Button(root, text = '2').pack(side = 'top') Button(root, text = '3').pack(side = 'right') Button(root, text = '4').pack(side = 'bottom') Button(root, text = '5').pack(fill = 'both') root.mainloop()

grid(). Размещает виджеты на сетке. Основные параметры: row/column – строка/столбец в сетке, rowspan/columnspan – сколько строк/столбцов занимает виджет. Пример:
from Tkinter import * root = Tk() Button(root, text = '1').grid(row = 1, column = 1) Button(root, text = '2').grid(row = 1, column = 2) Button(root, text = '__3__').grid(row = 2, column = 1, columnspan = 2) root.mainloop()

place(). Позволяет размещать виджеты в указанных координатах с указанными размерами.
Основные параметры: x, y, width, height. Пример:
from Tkinter import * root = Tk() Button(root, text = '1').place(x = 10, y = 10, width = 30) Button(root, text = '2').place(x = 45, y = 20, height = 15) Button(root, text = '__3__').place(x = 20, y = 40) root.mainloop()

Теперь для демонстрации других возможностей Tkinter, напишем простейший
Текстовый редактор
Без лишних слов приведу код:
from Tkinter import * import tkFileDialog def Quit(ev): global root root.destroy() def LoadFile(ev): fn = tkFileDialog.Open(root, filetypes = [('*.txt files', '.txt')]).show() if fn == '': return textbox.delete('1.0', 'end') textbox.insert('1.0', open(fn, 'rt').read()) def SaveFile(ev): fn = tkFileDialog.SaveAs(root, filetypes = [('*.txt files', '.txt')]).show() if fn == '': return if not fn.endswith(".txt"): fn+=".txt" open(fn, 'wt').write(textbox.get('1.0', 'end')) root = Tk() panelFrame = Frame(root, height = 60, bg = 'gray') textFrame = Frame(root, height = 340, width = 600) panelFrame.pack(side = 'top', fill = 'x') textFrame.pack(side = 'bottom', fill = 'both', expand = 1) textbox = Text(textFrame, font='Arial 14', wrap='word') scrollbar = Scrollbar(textFrame) scrollbar['command'] = textbox.yview textbox['yscrollcommand'] = scrollbar.set textbox.pack(side = 'left', fill = 'both', expand = 1) scrollbar.pack(side = 'right', fill = 'y') loadBtn = Button(panelFrame, text = 'Load') saveBtn = Button(panelFrame, text = 'Save') quitBtn = Button(panelFrame, text = 'Quit') loadBtn.bind("", LoadFile) saveBtn.bind("", SaveFile) quitBtn.bind("", Quit) loadBtn.place(x = 10, y = 10, width = 40, height = 40) saveBtn.place(x = 60, y = 10, width = 40, height = 40) quitBtn.place(x = 110, y = 10, width = 40, height = 40) root.mainloop()
Здесь есть несколько новых моментов.
Во-первых, мы подключили модуль tkFileDialog для диалогов открытия/закрытия файла. Использовать их просто: нужно создать объект типа Open или SaveAs, при желании задав параметр filetypes, и вызвать его метод show(). Метод вернёт строку с именем файла или пустую строку, если пользователь просто закрыл диалог.
Во-вторых, мы создали два фрейма. Фрейм предназначен для группировки других виджетов. Один содержит управляющие кнопки, а другой — поле для ввода текста и полосу прокрутки.
Это сделано, чтобы textbox не налезал на кнопки и всегда был максимального размера.
В-третьих, появился виджет Text. Мы его создали с параметром wrap=’word’, чтобы текст переносился по словам. Основные методы Text: get, insert, delete. Get и delete принимают начальный и конечный индексы. Индекс — это строка вида ‘x.y’, где x — номер символа в строке, а y — номер строки, причём символы нумеруются с 1, а строки — с 0. То есть на самое начала текста указывает индекс ‘1.0’. Для обозначения конца текста есть индекс ‘end’. Также допустимы конструкции вида ‘1.end’.
B в-четвёртых, мы создали полосу прокрутки (Scrollbar). После создания её нужно связать с нужным виджетом, в данном случае, с textbox. Связывание двустороннее:
scrollbar['command'] = textbox.yview textbox['yscrollcommand'] = scrollbar.set
Вот и всё. Tkinter – это, безусловно, мощная и удобная библиотека. Мы осветили не все её возможности, остальные — тема дальнейших статей.
Что такое Tkinter
Tkinter – это пакет для Python, предназначенный для работы с библиотекой Tk. Библиотека Tk содержит компоненты графического интерфейса пользователя (graphical user interface – GUI). Эта библиотека написана на языке программирования Tcl.
Под графическим интерфейсом пользователя (GUI) подразумеваются все те окна, кнопки, текстовые поля для ввода, скроллеры, списки, радиокнопки, флажки и другие элементы, которые вы видите на экране, открывая то или иное приложение. Через них вы взаимодействуете с программой и управляете ею. Все эти элементы интерфейса будем называть виджетами (widgets – штуковины).
В настоящее время почти все приложения, которые создаются для конечного пользователя, имеют GUI. Редкие программы, подразумевающие взаимодействие с человеком, остаются консольными. В предыдущих двух курсах мы писали только консольные программы.
Существует множество библиотек GUI, среди которых Tk не самый популярный инструмент, хотя с его помощью написано немало проектов. Он был выбран для Python по-умолчанию. Установочный файл интерпретатора Питона обычно уже включает пакет tkinter в составе стандартной библиотеки.
Tkinter можно представить как переводчик с языка Python на язык Tcl. Вы пишете программу на Python, а код модуля tkinter переводит ваши инструкции на язык Tcl, который понимает библиотека Tk.
Программы с графическим интерфейсом пользователя событийно-ориентированные. Вы уже должны иметь представление о структурном и желательно объектно-ориентированном программировании. Событийно-ориентированное ориентировано на события. То есть та или иная часть программного кода начинает выполняться лишь тогда, когда случается то или иное событие.
Событийно-ориентированное программирование базируется на объектно-ориентированном. Даже если мы не будем разрабатывать собственные классы, мы обязательно будем пользоваться теми, что есть в tkinter . Все виджеты – это объекты-экземпляры, создаваемые от встроенных классов.
События бывают разными. Сработал временной фактор, завершилась загрузка, пришло сообщение, кто-то кликнул мышкой или нажал Enter , начал вводить текст, переключил радиокнопки, прокрутил страницу вниз и так далее. Когда случается что-либо подобное, то, если был создан обработчик для соответствующего события, происходит выполнение определенной части программы, что приводит к какому-либо результату.
Tkinter импортируется стандартно для модуля Python любым из способов:
- import tkinter
- from tkinter import *
- import tkinter as tk
Можно импортировать отдельные классы, что делается редко. В данном курсе мы будем использовать выражение from tkinter import * .
Если необходимо, узнать установленную версию Tk можно через константу TkVersion:
>>> from tkinter import * >>> TkVersion 8.6
Чтобы написать GUI-программу, надо выполнить приблизительно следующее:
- Создать главное окно.
- Создать виджеты и выполнить конфигурацию их свойств (опций).
- Определить события, то есть то, на что будет реагировать программа.
- Описать обработчики событий, то есть то, как будет реагировать программа.
- Расположить виджеты в главном окне.
- Запустить цикл обработки событий.
Последовательность не обязательно такая, но первый и последний пункты всегда остаются на своих местах. Посмотрим все это в действии.
В современных операционных системах любое пользовательское приложение заключено в окно, которое можно назвать главным, так как в нем располагаются все остальные виджеты. Объект окна верхнего уровня создается от класса Tk модуля tkinter . Переменную, связываемую с объектом, часто называют root (корень):
root = Tk()
Пусть в окне приложения располагаются текстовое поле, метка и кнопка. Данные объекты создаются от классов Entry , Label и Button модуля tkinter . Сразу выполним конфигурацию некоторые их свойства с помощью передачи аргументов конструкторам этих классов:
ent = Entry(root, width=20) but = Button(root, text="Преобразовать") lab = Label(root, width=20, bg='black', fg='white')
Устанавливать свойства объектов не обязательно при их создании. Существуют еще пара способов, с помощью которых это можно сделать после.
Первым аргументом в конструктор виджета передается виджет-хозяин, то есть тот, на котором будет располагаться создаваемый. В случае, когда элементы GUI помещаются непосредственно на главное окно, родителя можно не указывать. То есть в нашем примере мы можем убрать root :
ent = Entry(width=20) but = Button(text="Преобразовать") lab = Label(width=20, bg='black', fg='white')
Однако виджеты не обязательно располагаются на root ‘е. Они могут находиться на других виджетах, и тогда указывать «мастера» необходимо.
Пусть в программе текст, введенный человеком в поле, при нажатии на кнопку разбивается на список слов, слова сортируются по алфавиту и выводятся в метке. Выполняющий все это код надо поместить в функцию:
def str_to_sort_list(event): s = ent.get() s = s.split() s.sort() lab['text'] = ' '.join(s)
У функций, которые вызываются при наступлении события с помощью метода bind , должен быть один параметр. Обычно его называют event , то есть «событие».
В нашей функции с помощью метода get из поля забирается текст, представляющий собой строку. Она преобразуется в список слов с помощью метода split . Потом список сортируется. В конце изменяется свойство text метки. Ему присваивается строка, полученная из списка с помощью строкового метода join .
Теперь необходимо связать вызов функции с событием:
but.bind('', str_to_sort_list)
В данном случае это делается с помощью метода bind . Ему передается событие и функция-обработчик. Событие будет передано в функцию и присвоено параметру event . Здесь событием является щелчок левой кнопкой мыши, что обозначается строкой » .
В любом приложении виджеты не разбросаны по окну как попало, а организованы, интерфейс продуман до мелочей и обычно подчинен определенным стандартам. Пока расположим элементы друг под другом с помощью наиболее простого менеджера геометрии tkinter – метода pack :
ent.pack() but.pack() lab.pack()
Метод mainloop экземпляра Tk запускает главный цикл обработки событий, что в том числе приводит к отображению главного окна со всеми «упакованными» на нем виджетами:
root.mainloop()
Полный код программы:
from tkinter import * def str_to_sort_list(event): s = ent.get() s = s.split() s.sort() lab['text'] = ' '.join(s) root = Tk() ent = Entry(width=20) but = Button(text="Преобразовать") lab = Label(width=20, bg='black', fg='white') but.bind('', str_to_sort_list) ent.pack() but.pack() lab.pack() root.mainloop()
В результате выполнения данного скрипта появляется окно, в текстовое поле которого можно ввести список слов, нажать кнопку и получить его отсортированный вариант:

Попробуем теперь реализовать в нашей программе объектно-ориентированный подход. Это необязательно, но позволяет связать/объединить вместе (вспомните про инкапсуляцию в ООП) виджет и функции, которые обрабатывают связанные с ним события, что концептуально более верно. В этом случае функции становятся методами.
Пусть группа из метки, кнопки и поля представляет собой один объект, порождаемый от класса Block . Тогда в основной ветке программы будет главное окно, объект типа Block и запуск окна. Поскольку блок должен быть привязан к главному окну, то неплохо бы передать в конструктор класса окно-родитель:
from tkinter import * root = Tk() first_block = Block(root) root.mainloop()
Теперь напишем сам класс Block :
class Block: def __init__(self, master): self.ent = Entry(master, width=20) self.but = Button(master, text="Преобразовать") self.lab = Label(master, width=20, bg='black', fg='white') self.but['command'] = self.str_to_sort self.ent.pack() self.but.pack() self.lab.pack() def str_to_sort(self): s = self.ent.get().split() s.sort() self.lab['text'] = ' '.join(s)
Здесь виджеты являются значениями полей объекта типа Block , функция-обработчик события нажатия на кнопку устанавливается не с помощью метода bind , а с помощью свойства кнопки command . В этом случае в вызываемой функции не требуется параметр event . В метод мы передаем только сам объект.
Больший смысл в определении собственного класса появляется, когда требуется несколько или множество похожих объектов-блоков. Допустим, нам нужно несколько блоков, состоящих из метки, кнопки, поля. Причем у кнопки каждой группы будет своя функция-обработчик клика.
Тогда можно передавать значения для свойства command в конструктор. Значение будет представлять собой привязываемую к кнопке функцию-обработчик события. Полный код программы:
from tkinter import * class Block: def __init__(self, master, func): self.ent = Entry(master, width=20) self.but = Button(master, text="Преобразовать") self.lab = Label(master, width=20, bg='black', fg='white') # self.but['command'] = eval('self.' + func) self.but['command'] = getattr(self, func) self.ent.pack() self.but.pack() self.lab.pack() def str_to_sort(self): s = self.ent.get().split() s.sort() self.lab['text'] = ' '.join(s) def str_reverse(self): s = self.ent.get().split() s.reverse() self.lab['text'] = ' '.join(s) root = Tk() first_block = Block(root, 'str_to_sort') second_block = Block(root, 'str_reverse') root.mainloop()
Выражение getattr(self, func) , где вместо func подставляется строка ‘str_to_sort’ или ‘str_reverse’, преобразуется в выражение self.str_to_sort или self.str_reverse .
При выполнения этого кода в окне будут выведены два однотипных блока, кнопки которых выполняют разные действия.

Класс можно сделать более гибким, если жестко не задавать свойства виджетов, а передавать значения как аргументы в конструктор, после чего присваивать их соответствующим опциям при создании объектов.
Практическая работа
Напишите простейший калькулятор, состоящий из двух текстовых полей, куда пользователь вводит числа, и четырех кнопок «+», «-«, «*», «/». Результат вычисления должен отображаться в метке. Если арифметическое действие выполнить невозможно (например, если были введены буквы, а не числа), то в метке должно появляться слово «ошибка».
Курс с примерами решений практических работ: pdf-версия
X Скрыть Наверх
Tkinter. Программирование GUI на Python