Introduction to Tkinter

image

Good day to all!

Tkinter is a cross-platform library for developing a graphical interface in Python ( since Python 3.0 it has been renamed to tkinter ). Tkinter stands for Tk interface, and is an interface to Tcl / Tk .
Tkinter is part of the standard Python distribution.

All of the code in this article is written for Python 2.x.
To make sure that Tkinter is installed and working, we use the standard Tkinter _test () function :

import Tkinter
Tkinter._test()

After executing this code, the following window should appear:



Great, now you can start writing a few simple programs to demonstrate the basic principles of Tkinter.

Hello world


Of course, where would it be without him. First of all, we need to create the main window by writing

from Tkinter import *
root = Tk()

Yes, yes, just one line, it’s not for you WinAPI (=. Now create a button, when clicked, the text will be displayed in the console:

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()

It's simple, isn't it? We create an instance of the Button class, specify the parent and, if desired, a list of parameters. There are many more options, such as font, border thickness, etc.
Then we attach the event to the button click (you can bind several different events depending on, for example, which mouse button our btn was pressed.
Mainloop () starts the event loop; until we call this function, our window will not respond to external irritants.

Packers

The pack () function is the so-called packer, or layout manager. He is responsible for how widgets will be located on the main window. For each widget, you need to call the wrapper method, otherwise it will not be displayed. There are three packers in total:

pack () . Automatically places widgets in the parent window. It has parameters side, fill, expand . Example:

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 () . Places widgets on a grid. Key parameters: row / column - row / column in the grid, rowspan / columnspan - how many rows / columns the widget occupies. Example:

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 () . Allows you to place widgets in the specified coordinates with the specified dimensions.
Main parameters: x, y, width, height . Example:

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()



Now to demonstrate other features of Tkinter, we will write the simplest

Text editor


Without further ado, I’ll give the code:

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()

There are several new points here.

First, we hooked up the tkFileDialog module for file open / close dialogs. Using them is simple: you need to create an object of type Open or SaveAs , optionally setting the filetypes parameter , and call its show () method . The method will return a string with the file name or an empty string if the user just closed the dialog.

Secondly, we created two frames. The frame is intended for grouping other widgets. One contains control buttons, and the other contains a text input field and a scroll bar.
This is done so that the textbox does not fit on the buttons and is always the maximum size.

Thirdly, a widget appearedThe Text . We created it with the wrap = 'word' parameter so that the text wraps around words. The main methods of Text: get, insert, delete . Get and delete accept start and end indices. An index is a line of the form 'x.y', where x is the number of the character in the line, and y is the number of the line, with the numbers numbered from 1 and the lines from 0. That is, the index '1.0' indicates the very beginning of the text. To indicate the end of the text there is an index 'end'. Structures of the form '1.end' are also allowed.

B fourthly, we have created a scrollbar ( Scrollbar ). After creating it, you need to associate it with the desired widget, in this case, with the textbox. Two-way binding:
scrollbar['command'] = textbox.yview
textbox['yscrollcommand'] = scrollbar.set

That's all. Tkinter is, of course, a powerful and convenient library. We have not covered all its possibilities, the rest is the topic of further articles.

Useful links:
http://ru.wikiversity.org
http://www.pythonware.com/

Also popular now: