0% found this document useful (0 votes)
40 views28 pages

JCA Python-Middle Lesson 04 1555673909

Uploaded by

k1tarii
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views28 pages

JCA Python-Middle Lesson 04 1555673909

Uploaded by

k1tarii
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Lesson # 4

Creating Windows
and Menus,
Options for Saving.
To-Do App Development

CONTENTS
Menus in Window Apps. Creating a Notepad App. . . . . . 3
To-Do App Development . . . . . . . . . . . . . . . . . . . . . . . . . . 12

Lesson materials are attached to this PDF file.


In order to get access to the materials, open the lesson in
Adobe Acrobat Reader.

2
Creating
Creating Windows
Windows andand Menus,
Menus, Options
Options forfor Saving.
Saving. To-DoApp
To-Do AppDevelopment
Development

Menus in Window Apps. Creating


a Notepad App
The tkinter library provides a possibility to create
window apps, dialog boxes, and menus. We have already
worked with tkinter widgets.
This time we will get acquainted with the Menu wid-
get and create a menu panel in our app.
A menu is usually arranged under the program title and
includes various tabs, items, and subitems. Every menu item
is an element that performs a specific command.
Let's consider the code editor Atom (see Figure 1 on
page 4). This software has many menu items, and each of
them includes lots of commands.
The LEGO MINDSTORMS Education EV3 for pro-
gramming robots also has a menu (see Figure 2 on page 4).

3
Lesson # 4
Lesson # 4

Figure 1

Figure 2

4
Creating
Creating Windows
Windows andand Menus,
Menus, Options
Options forfor Saving.
Saving. To-DoApp
To-Do AppDevelopment
Development

The Notepad app designed for text editing has a more


modest menu. The software has a simple and clear design,
but it still includes the main items that allow you to create a
new file, open a document, save it, close the app (Figure 3).

Figure 3

Let's create our notepad app with Python. This time we


will not just create a window and work through the program
interface but also create a menu. A menu is not just a part of
GUI, it is an element on the tools panel that provides quick
access to frequently used commands like open or save.

5
Lesson # 4
Lesson # 4

Let's begin to create an analog of Notepad (Figure 4).

Figure 4

First, import modules. We will need the tkinter library


again and the filedialog module from this package:
from tkinter import *
from tkinter import filedialog

The filedialog module creates dialog boxes.


It contains the functions askopenfilename() and
asksaveasfilename(). The first of them creates a dialog
box that opens a file located on your computer, and the
second saves it. Both functions return the name of the file
that you want to open or save.

6
Creating
Creating Windows
Windows andand Menus,
Menus, Options
Options forfor Saving.
Saving. To-DoApp
To-Do AppDevelopment
Development

Note that these functions do not open or save the file,


they only return its name.
Next, create two functions, each of them should perform
a specific command. One of them saves a file to your com-
puter, and the second opens a document in the program:
def save_file():

def open_file():

The commands that perform these functions will be


described later in this lesson.
Create the main window of the program:
root = Tk()

In tkinter, the menu instance is created with the Menu


class. The menu must be bound to the widget to which it
belongs.
Place the widget in the main program window:
menu = Menu(root)
root.config(menu=menu)

Our menu consists of the sections File and Help. Create


the File menu element:
file_menu = Menu(menu, tearoff=0)

The File tab must have various commands like create a


new document, open or save a file.

7
Lesson # 4
Lesson # 4

We will add subitems of the menu using the add_


command() method:
file_menu.add_command(label='New')
file_menu.add_command(label='Open..',
command=open_file)
file_menu.add_command(label='Save as..',
command=save_file)
file_menu.add_command(label='Exit', command=exit)

Create the Help menu in the same way:


help_menu = Menu(menu, tearoff=0)
help_menu.add_command(label='Help')
help_menu.add_command(label='About')

Add the menu to the panel under the name of the app
using the add_cascade() method:
menu.add_cascade(label='File', menu=file_menu)
menu.add_cascade(label='Help', menu=help_menu)

Great, our menu is ready (Figure 5)!

Figure 5

Now create an entry field like in the notepad. The field is


created with the Text widget. But its size is fixed by default.
If you maximize the window, this field will be centered at the
top of the window (Figure 6).
8
Creating
Creating Windows
Windows andand Menus,
Menus, Options
Options forfor Saving.
Saving. To-DoApp
To-Do AppDevelopment
Development

Figure 6

Let's fix this by adding the expand and fill properties.


The fill property specifies whether the element fills
the entire space. It can take values X and Y, meaning that it
can be expanded along the X-axis, Y-axis, or BOTH which
means that it fills the available space. Since we want to fill the
entire window, use the last parameter. The expand property
expands the content to fill the window.
Create an entry field that will resize when the window
resizes:
text = Text(root)
text.pack(expand=YES, fill=BOTH)

9
Lesson # 4
Lesson # 4

We have created the design of the app, but the commands


Open as… and Save as… do nothing at the moment.
Let's write the functions that will allow us to open and
save text files in the notepad. To open the dialog box, access
the asksaveasfilename() method. If the user enters a file
name, this file will be saved on his computer:
def save_file():
file_name = filedialog.
asksaveasfilename(initialdir='/', title='Select file',
filetypes=(('Text Documents',
'*.txt'), ('all files', '*.*')))
if file_name:
f = open(file_name, 'w')
text_save = str(text.get(1.0, END))
f.write(text_save+'\n')
f.close()

Now you can save the document on your device (Figure


7).

10
Creating
Creating Windows
Windows andand Menus,
Menus, Options
Options forfor Saving.
Saving. To-DoApp
To-Do AppDevelopment
Development

Figure 7

Write the function that will open files. This time we will
use the askopenfilename() method that opens the dialog
box. The content of the .txt file will be displayed in the text
area thus making our app a real notepad.
def open_file():
file_name = filedialog.
askopenfilename(initialdir='/', title='Open file',
filetypes=(('Text Documents',
'*.txt'), ('all files', '*.*')))
if file_name:
f = open(file_name, 'r')
text_open = f.read()

11
Lesson # 4
Lesson # 4

if text_open != NONE:
text.delete(1.0, END)
text.insert(END, text_open)

You can expand the app menu as you like and add a
certain command to each of the items.

To-Do App Development


We all have a number of tasks that should be done,
starting with homework and ending with meeting friends.
Of course, you can rely on your memory or write your tasks
in a notepad, or you can create an app for this!
This app will allow you to write all the things that you
should do and remove them after they are done.
To-Do by Microsoft is one of the task management apps
worth mentioning (Figure 8).

Figure 8

12
Creating
Creating Windows
Windows andand Menus,
Menus, Options
Options forfor Saving.
Saving. To-DoApp
To-Do AppDevelopment
Development

Another interesting task manager is Google Keep, where


a user can add her tasks (Figure 9).

Figure 9

Let's develop our app to organize all the tasks: To-Do


(see Figure 10 on page 14).
Let's create an easy-to-use app: the user can add a task in
a list and remove one or all tasks of the list. Our app will also
allow getting a random task, sorting the list, or learning the
overall number of tasks.

13
Lesson # 4
Lesson # 4

Figure 10

Import all modules required for our program:


from tkinter import *
from tkinter import messagebox
import random

Create two variables to store window size:


HEIGHT = 600
WIDTH = 600

14
Creating
Creating Windows
Windows andand Menus,
Menus, Options
Options forfor Saving.
Saving. To-DoApp
To-Do AppDevelopment
Development

Next, create an empty list to store tasks:


tasks = []

Then create functions that will manage tasks in the list:


def update_listbox():

def add_task():

def del_one():

def del_all():

def sort_asc():

def sort_desc():

def choose_random():

def show_number_of_tasks():

15
Lesson # 4
Lesson # 4

Return to the creation of the main program window.


Set a title and size for it and forbid the user to resize the
window:
root = Tk()
root.title('My Super To-Do List')
root.geometry('%dx%d' % (WIDTH, HEIGHT))
root.resizable(False, False)

Set a background image for the main window:


img = PhotoImage(file='img/todo_bg.gif')
background_label = Label(root, image=img)
background_label.place(relwidth=1, relheight=1)

Set a style, font size, and background color for all ele-
ments:
root.option_add('*Font', '{Comic Sans MS} 10')
root.option_add('*Background', 'white')

The main window is ready (Figure 11)!

It is time to place buttons, labels, and an entry field in the


program window. Create a frame with all widgets arranged
(Figure 12):
frame = Frame(root, bd=10)
frame.place(relx=0.1, rely=0.1, relwidth=0.8,
relheight=0.8)

16
Creating
Creating Windows
Windows andand Menus,
Menus, Options
Options forfor Saving.
Saving. To-DoApp
To-Do AppDevelopment
Development

Figure 11

Figure 12

17
Lesson # 4
Lesson # 4

Then add two labels in the upper part of the window.


One of them will be the title of our program, and the second
will display a random task or the number of tasks in the list.
Add the entry field after the Label widgets (Figure 13):
label_title = Label(frame, text='My Super To-Do
List', fg='dark blue', font='{Comic Sans MS} 16')
label_title.place(relx=0.3)

label_display = Label(frame, text='')


label_display.place(relx=0.3, rely=0.1)

text_input = Entry(frame, width=15)


text_input.place(relx=0.3, rely=0.15, relwidth=0.6)

Figure 13

Move on to the creation of buttons. Place them one by


one in the left part of the frame. Every button will execute a
specific command, so set the command parameter for each of
them (see Figure 14 on page 20):

18
Creating
Creating Windows
Windows andand Menus,
Menus, Options
Options forfor Saving.
Saving. To-DoApp
To-Do AppDevelopment
Development

# Buttons
button_add_task = Button(frame, text='Add task',
command=add_task)
button_add_task.place(rely=0.15, relwidth=0.25)

button_del = Button(frame, text='Delete',


command=del_one)
button_del.place(rely=0.25, relwidth=0.25)

button_del_all = Button(frame, text='Delete All',


command=del_all)
button_del_all.place(rely=0.35, relwidth=0.25)

button_sort_asc = Button(frame, text='Sort (A-Z)',


command=sort_asc)
button_sort_asc.place(rely=0.45, relwidth=0.25)

button_sort_desc = Button(frame, text='Sort (Z-A)',


command=sort_desc)
button_sort_desc.place(rely=0.55, relwidth=0.25)

button_random = Button(frame, text='Choose Random',


command=choose_random)
button_random.place(rely=0.65, relwidth=0.25)

button_number_of_tasks = Button(frame, text='Number


of Tasks', command=show_number_of_tasks)
button_number_of_tasks.place(rely=0.75,
relwidth=0.25)

19
Lesson # 4
Lesson # 4

button_exit = Button(frame, text='Exit',


command=exit)
button_exit.place(rely=0.85, relwidth=0.25)

Figure 14

So, by this time only the field to display tasks is missing.


The tkinter module has the Listbox widget that
allows displaying a list of elements. This list can contain only
text elements, and all elements will have the same font and
color.
20
Creating
Creating Windows
Windows andand Menus,
Menus, Options
Options forfor Saving.
Saving. To-DoApp
To-Do AppDevelopment
Development

Depending on the widget settings, the user can select


one or more items from the list.
listbox = Listbox(frame)
listbox.place(relx=0.3, rely=0.24, relwidth=0.6,
relheight=0.6)

Declare the main loop of the app:


root.mainloop()

This can finish the creation of GUI. Let's move on to the


description of functions, or the program will turn out to be
useless since buttons do not fulfill their purpose.
Every time we add or remove a task, the Listbox content
must be updated. So create a function that will update the list
content:
def update_listbox():
listbox.delete(0, END)
for task in tasks:
listbox.insert(END, task)

Program the Add Task button. After the user clicks on it,
a check will be triggered. The program will ask if the user has
entered anything in the task field. If the answer is yes, a new
task will appear in the field. If the field is empty, an alert will
be displayed (see Figure 15 on page 22).

21
Lesson # 4
Lesson # 4

def add_task():
task = text_input.get()
if task != '':
tasks.append(task)
update_listbox()
else:
messagebox.showwarning('Warning', 'Enter
the task in the input box, please.')
text_input.delete(0, END)

Figure 15

After the user completes the task, he should remove it.


Write a function that will remove the selected element from
the list (Figure 16):
def del_one():
task = listbox.get('active')
if task in tasks:
tasks.remove(task)
update_listbox()

22
Creating
Creating Windows
Windows andand Menus,
Menus, Options
Options forfor Saving.
Saving. To-DoApp
To-Do AppDevelopment
Development

Figure 16

Then program the Delete All button.


Many apps require the user to confirm the action before
this kind of command is executed. Let's create a dialog that
will appear upon click on the Delete All button. We should
ask the user whether he is sure that he wants to delete all
list items. As soon as the action is confirmed, the list will be
cleared (Figure 17):
def del_all():
confirmed = messagebox.askyesno('Please
Confirm', 'Do you really want to delete all?')
if confirmed:
global tasks
tasks = []
update_listbox()

Figure 17

23
Lesson # 4
Lesson # 4

Let's add a possibility to sort the list in the ascending and


descending orders. Python uses a built-in sort() method
that arranges elements in the ascending order. This method
allows us to order the list (Figure 18):
def sort_asc():
tasks.sort()
update_listbox()

Figure 18

The arrangement of elements in the descending order is


done as follows: order the elements with the sort() method
and apply the reverse() (Figure 19):
def sort_desc():
tasks.sort()
tasks.reverse()
update_listbox()

24
Creating
Creating Windows
Windows andand Menus,
Menus, Options
Options forfor Saving.
Saving. To-DoApp
To-Do AppDevelopment
Development

Figure 19

When you develop an app, it is important to remember


that it must be unique and stand out among similar products.
The feature of our program is to get a random task and
learn the overall number of tasks in the list (Figures 20 and
21):

Figure 20

25
Lesson # 4
Lesson # 4

Figure 21

def choose_random():
if len(tasks) > 0:
task = random.choice(tasks)
label_display['text'] = task
else:
messagebox.showwarning('Warning', 'No tasks')

def show_number_of_tasks():
number_of_tasks = len(tasks)
message = 'Number of tasks: %s' % number_of_tasks
label_display['text'] = message

The app is ready!

26
Creating
Creating Windows
Windows andand Menus,
Menus, Options
Options forfor Saving.
Saving. To-DoApp
To-Do AppDevelopment
Development

You can use the above code to develop your unique app.
An unusual design and interesting implementation will
only make your To-Do app better.
Look at several solutions offered by other developers.
Habitica is implemented as a game (Figure 22).

Figure 22

Todoist for mobile and desktop devices is also worth


mentioning (Figure 23).

Figure 23

27
Lesson # 4
Creating Windows and Menus,
Options for Saving.
To-Do App Development

© STEP IT Academy
www.itstep.org

All rights to protected pictures, audio, and video belong to their authors or legal owners.
Fragments of works are used exclusively in illustration purposes to the extent justified by
the purpose as part of an educational process and for educational purposes in accordance
with Article 1273 Sec. 4 of the Civil Code of the Russian Federation and Articles 21 and 23
of the Law of Ukraine “On Copyright and Related Rights”. The extent and method of cited
works are in conformity with the standards, do not conflict with a normal exploitation of
the work, and do not prejudice the legitimate interests of the authors and rightholders.
Cited fragments of works can be replaced with alternative, non-protected analogs, and
as such correspond the criteria of fair use.
All rights reserved. Any reproduction, in whole or in part, is prohibited. Agreement of the
use of works and their fragments is carried out with the authors and other right owners.
Materials from this document can be used only with resource link.
Liability for unauthorized copying and commercial use of materials is defined according
to the current legislation of Ukraine.

You might also like