Institute of Computer Science
  1. Courses
  2. 2018/19 fall
  3. Computer Programming (Narva College) (SVNC.00.054)
ET
Log in

Computer Programming (Narva College) 2018/19 fall

  • Home
  • Grading
  • Links

Before session 13

Before next class session, please read the following material about the graphical user interface module tkinter, and watch the video about regular expressions.

1. GUI in Python, using tkinter

Python provides various packages for developing graphical user interfaces (GUIs). The most commonly used one is tkinter. Tkinter is shipped together with any Python distribution (no supplementary modules are required in order to run scripts using tkinter).

Tkinter is the standard Python interface to the Tk GUI toolkit (What is Tk? read here). In other words, tkinter is an open source, portable GUI library designed for the use in Python scripts.

Python combined with tkinter provides a fast and easy way to create GUI applications (example). All you need to do is to perform the following steps:

  • import the tkinter module
  • create the main window of the application
  • add one or more widgets to the application
  • enter the main loop which waits for events (e.g. clicking a button, pressing a key, an operating system asking to quit an application etc.) and handle them accordingly

Example

from tkinter import *
window = Tk()
# Widgets will be added here later...
window.mainloop()

This program creates a window:

Widgets

Tkinter in Python comes with a large number of useful widgets. Widgets are standard graphical user interface (GUI) elements, such as buttons, labels and text boxes, used in a GUI application. A complete list of widgets and their descriptions can be found here.

The following program demonstrates basic Tk widgets:

from tkinter import *
from tkinter import messagebox

# this function is executed if the button is pressed 
def sayHello():
    say = 'Hello ' + name.get()
    messagebox.showinfo(message=say)

# define size and title of the window
window = Tk()
window.title("Say Hello")
window.geometry("300x100")

# label
labelName = Label(window, text="Name")
labelName.place(x=5, y=5)

# text field
name = Entry(window)
name.place(x=70, y=5, width=150)

# button; function sayHello is associated with a button
but = Button(window, text="Say Hello!", command=sayHello)
but.place(x=70, y=40, width=150)

# Enter the main event loop
window.mainloop()

If you run the program, you will see a small window containing a text box and a button. Once the text is entered and the button is clicked on, a greeting is displayed.

Pay attention to the place() method. This method sets the coordinates of the widget (units are pixels). Unlike the coordinate system in the Turtle module, the point (0,0) is located in the upper left corner of the window and the coordinates increase to the right and down.

More widgets can be found in Tk tutorial.

Canvas

One of the most exciting Tk widgets is a canvas. The canvas is a rectangular area intended for drawing pictures or other complex layouts. You can place graphics, pictures, text, etc. on a canvas. The following program demonstrates some possibilities how to use the canvas:

from tkinter import *
from tkinter import font #we can change the font of text

window = Tk()
window.title("Canvas")
area = Canvas(window, width=600, height=600, background="white")
area.grid() #this geometry manager organizes widgets into a table-like structure 

# one line (x0, y0, x1, y1)
area.create_line(30, 40, 300, 40)

# several lines (any number of coordinate pairs)
area.create_line(30,60,  300,60,  300,100,  60,100)

# change the width and color of the lines
area.create_line(30, 130, 300, 130, width=4, fill="red")

# different line style
area.create_line(30, 150, 300, 150, width=5, dash=(5, 1, 2, 1), arrow=LAST)

# dash lines: connect the endpoints and color the content
# colors can also be set in rgb
# check http://www.colorpicker.com/
area.create_polygon(30,160,  300,160,  300,200,  60,200, fill="#95BD9D")

# rectangle
area.create_rectangle(30,260,  300,300)

# oval
area.create_oval(30,260,  300,300, width=2, outline="blue", fill="wheat")

# try to move the mouse over this oval
area.create_oval(330, 330, 400, 400, fill="gray", activefill="pink")

# if you want to choose a font for the text, first create the font
big_font = font.Font(family='Helvetica', size=32, weight='bold')
area.create_text(30, 500, text="Tere!", font=big_font, anchor=NW)

window.mainloop()

For the project, it might be helpful to look at the following examples with tkinter.

If you would like to get more information about tkinter, check the following links:

  • Python Tkinter
  • Tkinter intro
  • Python GUI – tkinter

2. Regular expressions

Slides in English and in Russian

Textbook Text-book

Helpful link Quick Guide

3. Test

Go to Moodle and take the test on graphics and regular expressions.

4. Examples

Study the following examples on the graphical user interface module tkinter and regular expressions.

Example 1. Flag

The following program displays a window called "Flag". The program draws (using tkinter and its widget – canvas) a flag of Sillamäe (a town in Estonia).

from tkinter import *

window = Tk()
window.title("Flag")
area = Canvas(window, width=880, height = 560)

area.create_rectangle(0, 0, 880, 560, fill="blue", outline="blue")

for i in range(5):
    area.create_rectangle(0+i*80, 560-3*70-i*70, 2*80+i*80, 560-i*70, fill="yellow", outline="yellow")
    area.create_rectangle(880-2*80-i*80, 560-3*70-i*70, 880-i*80, 560-i*70, fill="yellow", outline="yellow")

area.create_rectangle(880-6*80, 0, 880-5*80, 70, fill="yellow", outline="yellow")

area.pack()
window.mainloop()

Example 2. Room codes at Liivi 2 read from the file

The file schedule.txt contains data about lectures/practical sessions (course name, place and time). The following program reads the data from the file and extracts the codes of the rooms at Liivi 2 using regular expressions. The program also prints out these codes.

import re
fname = input("Please enter a file name: ")

try:
    ffile = open(fname)
except:
    print('File cannot be opened:', fname)
    exit()

for line in ffile:
    x = re.findall('Liivi 2 - ([0-9]+)', line)
    if len(x) > 0:
        for el in x:
            print(el)

5. Solve and submit

Exercise 1. Draw a ship

Write a program that uses tkinter and its widget canvas to draw a picture of ship in the window with white background. The title of the window has to be "Ship".

PS: check the additional material

Exercise 2. Usernames from urls

At the University of Tartu, every user of the Study Information System (a student or a member of staff) has his/her home directory. The user can create a webpage on the university server. The url for his/her webpage would be http://www.ut.ee/~username/ (e.g. http://www.ut.ee/~vilo/).

Write a program that prompts the user for a file name. The file contains urls and other information. The program has to read the file line by line, look for the user names on University of Tartu web servers in urls (using regular expressions) and print the names out. User names on other web servers and other lines of information should be ignored.

If the file urls.txt contains the following lines:

 http://www.ut.ee/~koit/KT/index_eng.html
 Lecture lasts ~90 minutes
 http://butler.cc.tut.fi/~jorma/
 https://www.ut.ee/et/oppimine
 http://www.ut.ee/~vilo/
 http://www.ut.ee/~kiho/
 "x ~ y" means that x and y are of the same order of magnitude

then the output of the program has to be

 Please enter a file name: urls.txt
 The user names are:
 koit
 vilo
 kiho

Go to Moodle and upload your solutions into Session 13 homework.

Check the additonal material if you have not done it yet :)

  • Institute of Computer Science
  • Faculty of Science and Technology
  • University of Tartu
In case of technical problems or questions write to:

Contact the course organizers with the organizational and course content questions.
The proprietary copyrights of educational materials belong to the University of Tartu. The use of educational materials is permitted for the purposes and under the conditions provided for in the copyright law for the free use of a work. When using educational materials, the user is obligated to give credit to the author of the educational materials.
The use of educational materials for other purposes is allowed only with the prior written consent of the University of Tartu.
Terms of use for the Courses environment