Before session 4
Before next class session, read the text material about the graphical user interface module tkinter, and watch the videos about regular expressions.
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 keys, 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). Differently from the coordinate system in the Turtle module, the point (0,0) is located in the upper left corner of the window and the coordinates grow 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 options 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="Hello!", font=big_font, anchor=NW) window.mainloop()
For the project, it might be helpful to use the following examples with tkinter.
If you like to get more information about tkinter, check the following links:
Regular expressions
Test
Go to Moodle and take the fourth test on graphics and regular expressions.
Exercises
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 the codes out.
import re fname = input("Please enter a file name: ") try: ffile = open(fname) except: print('File cannot be opened:', fname) else: for line in ffile: x = re.findall('Liivi 2 - ([0-9]+)', line) if len(x) > 0: for el in x: print(el)
Exercise 1. Traffic sign
Choose a traffic sign (examples: https://en.wikipedia.org/wiki/Traffic_sign). Write a program that uses tkinter and its widget canvas to draw the traffic sign in the window with white background. The title of the window has to be "Traffic Sign".
PS: check the additional material
Exercise 2. Username from url
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 program has to read the file line by line, look for the user names (using regular expressions) and print the names out.
If the file urls.txt contains the following lines:
http://www.ut.ee/~koit/KT/index_eng.html Lecture lasts ~90 minutes 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 put your solutions into Exercises 4.
Check the additonal material if you have not done it yet :)