Homework for Week 15
Before next class session, please read the following material about the graphical user interface module Tkinter, and watch the videos about regular expressions.
GUI in Python, using Tkinter
Python provides a variety of packages for developing graphical user interfaces (GUIs). The most common of them is Tkinter, which belongs to any Python distribution. Tkinter is a standard Python interface in the Tk GUI toolkit. In other words, Tkinter is an open source, portable GUI library designed for the use in Python scripts. Python, in conjunction with Tkinter. provides a fast and easy way to create GUI applications (example).
To use Tkinter, you need 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 the application window:
Widgets
Tkinter has a large number of useful widgets. These are standard graphical user interface (GUI) elements, such as buttons, labels and text boxes, used in a GUI application. Complete list of widgets and their descriptions can be found here.
The following program demonstrates some 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 the size and the 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 box 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 the 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 the 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="Mercury", font=big_font, anchor=NW) window.mainloop()
Also look at more examples with Tkinter.
If you would like to get more information about Tkinter, check the following links:
Regular expressions
Quiz
Go to Moodle and solve the quiz about graphics and regular expressions.
Examples
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.
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 in Liivi 2 read from the file
The file schedule.txt contains data about lectures and practice sessions (course name, place and time) in the University of Tartu. The following program reads the data from the file and extracts the codes of the rooms in the Institute of Computer Science building Liivi 2, using regular expressions. The program also prints the codes on the screen.
import re fname = input("Please enter filename: ") 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)
Exercises
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".
2. Strong password
Write a function is_strong that takes a password (a string) as its argument and uses regular expressions to check whether the password is strong. A strong password consists of at least eight characters, contains letters in both uppercase and lowercase, and at least one digit.
>>> is_strong("k4A8cd82B") True >>> is_strong("Bdy5Cez") False >>> is_strong("password") False
Hint. You may test the password against multiple regular expressions.
Submit your solutions
Go to Moodle and upload your solutions under homework for Session 15 (home1.py and home2.py). Note that the autograder of exercise 1 doesn't check the output image.