© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2022
K. WilsonThe Absolute Beginner's Guide to Python Programminghttps://doi.org/10.1007/978-1-4842-8716-3_10

10. Building an Interface

Kevin Wilson1  
(1)
London, UK
 

Modern computer applications are built with graphical user interfaces in mind. The user interacts with the application using windows, icons, menus, and a mouse pointer rather than console-based I/O.

To create a graphical user interface using Python, you’ll need to use Tkinter (Tk interface). This module is bundled with standard distributions of Python for all platforms.

Creating a Window

The first thing you need to do is import the Tkinter module into your program. To do this, use
from tkinter import *
To create a window , use the Tk() method:
window = Tk()
Add a title:
window.title('Window Title')
Set the initial size and position of the window. Use the .geometry() method .
window.geometry("800x600+50+20")

The first two numbers, in this case “800x600,” set the window size . Set this to the desired window size in pixels. This could be 1280x720, 1920x1080, and so on.

The second two numbers, in this case “50+20,” set the initial position of the window on the screen using x and y coordinates.

A module depicts how to create a window. The window size is given as 800 by 600, and its left indention position is 50, and the top at 20.

Let’s take a look at a program. Open window.py. Here, we’ve created a window. You can do this using the Tk() function and assign it to a window object.

A window has a code for creating a window that includes its initial size, position, and title. An untitled and blank window is also included.

We’ve sized the window, so that is 640 pixels wide by 480 pixels high. We’ve also positioned the window 500 pixels across from the top left by 20 pixels down. You can do this using the .geometry() method . This is the initial size and position of the window on screen.

We’ve also added a window title. You can do this using the .title() method . This helps to identify your app.

Finally, to make the window appear, we need to enter the Tkinter event loop. You can do this with the .mainloop() method :
window.mainloop()

This is an infinite loop used to run the application and is called an event loop. The .mainloop() method waits for an event such as a keypress or mouse click events from the window system and dispatches them to the application widgets (frames, buttons, menus, etc.).

Adding Widgets

Widgets are standard items for building a graphical user interface using Tkinter.

Menus

Let’s add a menu . You can create a menu bar using the Menu() function. Assign it to an object (e.g., menubar) and attach it to your main window.

A window has the menu bar indicated on top. Below are the file menu and menu commands.

Now you need to create the individual menus (such as “file,” “edit,” etc.) on the menubar.
filemenu = Menu(menubar-to-add-to, menu-style)
Add the menus to the menubar:
menubar.add_cascade(menu-label, menu-to-add-to)
For each menu you create (e.g., filemenu), you need to create each menu command (such as “new,” “save,” “exit,” etc.):
filemenu.add_command(command-label, function)
Finally, add the menubar you’ve created to the main window:
window.config(menu-to-add)

Let’s take a look at a program. Open the file menu.py. Here, we’ve written the program as described earlier.

A window has a program for creating a window, menu bar, menu, menu commands, and adding a menu. A window pop-up has a file given on a menu bar.

The Canvas

The canvas is used to draw and create graphics and layouts. This is where you place your graphics, text, buttons, and other widgets to create your interface.

To create a canvas, use
myCanvas = Tkinter.Canvas (parent-window, bg="sky blue", height=300, width=300)

Use parent-window to attach the canvas to your window. Use height and width to size your canvas.

Use bg to set the background color. Open colorchart.py and run the program. This will create the color chart shown here.

A window depicts a color chart. The palette includes the color names and their corresponding numbers.

Select the name of the color from the chart to use in the bg parameter .

Let’s draw a shape on the canvas:
rect = myCanvas.create_rectangle
        (100, 100, 25, 50, fill="yellow")

The first two numbers are the x and y coordinates on the canvas. The second two numbers are the length and width.

A canvas has a yellow rectangle on its upper left-hand side.

You can also draw a polygon.

A two-line code for creating a triangle includes three sets of numbers corresponding to the three lines to be drawn.

In this example , we’re creating a triangle. A triangle has three sides, so we need to draw three lines. The first two numbers indicate the start point of the first line; the second two numbers indicate the end point of the first line, and so on. Let’s take a look.

A canvas has measurement bars on the top and left. A triangle on it has an apex with starting points 100, 150, and legs at 57, 255, and 143, 255.

Try drawing a pentagon . A pentagon has five sides, so you need to draw five lines:
pent = myCanvas.create_polygon
     (100,150, 52,185, 71,240, 129,240, 148,185,
     fill="lime green")

Images

You can add images to your canvas. Have a look at images.py. To load the image, use the PhotoImage() function.

A window has a code on the left panel for adding images to a canvas. On the right panel is a canvas with an image of a rocket ship on it.

To paste the image on your canvas, use the .create_image() method.

Buttons

You can add command buttons to your canvas. To do this, use the Button() function.

Have a look at buttons.py:
myButton = Button(window, text="label", command)

Use window to specify the name of the window the button is to go on.

Use command to specify the function you want to call to handle what the button does. You can call existing functions or define your own functions to do this.

Use the .pack method to add the button to your window:
myButton.pack()

Message Boxes

You can add message boxes to your programs. To do this, you will need to import the message box functions from the Tkinter module. You can do this using the import command:
from tkinter import messagebox

You can create different types of message boxes: an info box, a warning box, an error box, and a box that asks for a yes/no response.

Four examples of message boxes and their corresponding icons. The first 3 have the ok button, and the fourth has the yes and no buttons.

messagebox.showinfo('Message Title', 'Message')
If you’re asking the user for a yes/no response, you’ll need to process this:
response = messagebox.askquestion
     ('Message Box' , 'Question...')
if response == 'yes' :
     executed if user clicks 'yes'
else :
     executed if user clicks 'no'

Let’s have a look at messagebox.py.

A window has a code on the left for processing yes and no responses. On the right are two message boxes indicating the highlighted yes and ok buttons.

Text Field

Use the Entry() function to create your text field :
userInput = Entry( window )
Use the .pack() method to add the field to your window:
userInput.pack()
To get the data from the text field, use the .get() method:
userInput.get()

Let’s add these to the program. Have a look at textfield.py. Here, we’ve added a text field to the canvas under the command button.

A window has a code on the left panel. On the right is a canvas with a text field, a click me button and a text message box with an ok button.

We’ve also added code in the dialog() function to get the data from the text field and display it in a message box.

The dialog() f unction is called when the “Click Me” button is clicked.

Run the program and see what it does.

Listbox

Use the Listbox() function to create your listbox :
list = Listbox(window)
Use the .insert() method to add items to the listbox:
list.insert(1, 'Item One')
Use the .pack() method to add the listbox to your window. Use the padx and pady parameters to add some padding to space out your listbox in the window.
list.pack(padx=20, pady=20)
Use the .curselection() method to get the index of the item selected by the user. Remember, the first item’s index is 0.
selectedItem = list.curselection()
Use the .get() method to return the item:
list.get (selectedItem)

Let’s take a look at a program. Open listbox.py.

A window has a code for creating a list box. On the right is a canvas with a list box, a click me button, and a message box with an ok button selected.

Checkbox

Use the Checkbutton()function to create each of your checkboxes :
box1 = Checkbutton(window, text="Red",
          variable=box1Checked, onvalue=1)
You’ll need to create a variable for each checkbox to assign its “onvalue” if the user clicks the checkbox:
box1Checked = IntVar()
The variables you created will either be 1 or 0. Onvalue is set to 1, so the variable will be set to 1 when the user clicks the checkbox. Use the .get() method to get the value.
if box1Checked.get() == 1:
    messagebox.showinfo( 'Msg' , "Red" )
Use the .pack() method to add each of your checkboxes to your window:
box1.pack()

Let’s take a look at a program. Open checkbox.py.

A window has a code for getting the value when a checkbox is clicked and for creating and adding checkboxes to a window.

When you run the program , you can select any of the checkboxes. When you click the button, the function reads which checkbox is selected and returns the value.

A canvas has the variables red, green, and blue, where the checkbox beside green is ticked, a click me button and a message box for green.

Labels

You can create labels to label text fields and other items on your interface. To do this, use Label():
textLabel = Label(window, text="Enter Name:")
Use pack() to add the label to your window:
textLabel.pack()

Label Frame

The LabelFrame is used to group related widgets, such as checkboxes, radio buttons, or text fields.

First, you need to create your label frame group. You can do this with LabelFrame() as follows:
group1 = LabelFrame(window, text="label", padx=5, pady=5)
Use the first parameter window to attach the group to your main window. Next, you need to add your widgets to your group. You can do this in the usual way, except you need to specify in the widget functions which widget to attach to. So to add our text label, specify the widget to attach to using the first parameter (our labelframe defined earlier is called group1, so use group1 underlined in the following).
textLabel = Label(group1, text="Name: ")
Add your widgets to your window in the usual way:
textLabel.pack(side=LEFT)

Let’s take a look at a program. Open labelframe.py.

A window has a code for creating a label frame-group. On the right panel is a text label titled contact details, and a text field for name.

Here, we’ve created a text label and a text field inside the labelframe group (group1).

Interface Design

Now that we know how to create a window, menus, and add different types of widgets, we’ll take a look at how to lay them out in the window to create a usable interface.

You can do this using the grid layout manager. Let’s take a look at an example. Open the file gridlayout.py.

Use the .grid() method to place the widgets in the window according to the grid layout. Use row and column parameters to specify which cell in the grid to place the widget. Use the padx and pady parameters to add some spacing around your widgets in the grid.

A window has a code where some lines are boxed with arrows pointed at widgets on a grid on the right. The grid has two columns and two rows.

Here, we’ve placed a text label in row 1, column 1. There is a text field in row 1, column 2. We’ve placed a command button in row 2, column 2.

When you run the program, you’ll see the result as shown here:

A grid layout has two columns and two rows. On the top row is a text field titled enter name, and below is an ok button.

Let’s design a simple interface for a unit converter app. To design this interface, we’ll divide the window up into three rows and five columns.

A window has five columns and three rows, which contains a geometrical image with labels on the right.

Now, we’ll place a logo on the left-hand side and span it across two columns and down three rows:
img = PhotoImage(file="logo.png")
imgLbl = Label(window, image=img)
imgLbl.grid( row = 1, column = 1, padx = 10,
   pady=10, columnspan=2, rowspan=3)
We’ll also place a label in row 1, column 3:
textLabel = Label(window, text="Convert:")
textLabel.grid( row = 1, column = 3,
    padx = 10, pady=10)
A drop-down box in row 1, column 4:
conversions.grid( row = 1, column = 4, padx = 10, pady=10)
A text field in row 2, column 4, with a button in row 2, column 5:
userInput.grid( row = 2, column = 4, padx = 10, pady=10)
A label at the bottom in row 3, column 4, to show the result:
textLabel.grid( row = 3, column = 4, padx = 10, pady=5)
Add a command button to row 2, column 6:
myButton.grid( row = 2, column = 6,
    padx = 10, pady=10)

Let’s take a look at the program. Open the file converter.py. Here, we’re adding the widgets to the grid using the .grid() method .

A code for adding widgets to a grid. It includes adding an image, label, combo box, text field, and creating a label, and a button, among others.

We’ve used the padx and pady parameters to space out the widgets in the grid layout.

That’s the interface sorted. As it stands, the program won’t do anything if you click the button or enter a number into the text field.

We need to write a function to take care of this and call it when the button is clicked.

Declare the function in the usual way. We’ll call this one convert() .

A 17-line code for an outcome or result when a button is clicked or an entry is made in a text field on an interface.

You’ll need to read the selection from the combo box. You can do this with the .current() method . The first item in the combo box has an index of 0, the second is 1, and so on. Use an if statement to separate the calculations for each selection in the combo box.
if conversions.current() == 0:
Next, you’ll need to get the data from the text field. You can do this with a .get() method on the text field. Remember to cast the data type to a float, as the data from a text field is a string.
n = float (userInput.get())

Perform the calculation and return the result to the blank text label in row 3, column 4, of the grid.

Now, when you run the program , you’ll get a nicely laid out interface.

A unit converter window has a logo on the left. On the right is a text field labeled convert, a dropdown menu, an entry box, and an ok button.

Summary

In this chapter, you learned the following:
  • To create a graphical user interface using Python, you’ll need to use Tkinter (Tk interface).

  • Widgets are standard items for building a graphical user interface using Tkinter.

  • The canvas is used to draw and create graphics and layouts. This is where you place your graphics, text, buttons, and other widgets to create your interface.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.147.215