Chapter 2:
Make the User Interface

Now it’s time to add a proper display and button to our app. When clicked, the button will display a random book from the library collection in our Sheet.

We’ll make it work by writing some more client-side Python code that runs in the browser.

Step 1: Add a title

First, let’s give the app a title. We’ll call it BookFinder! Drag a new Label on to the “Drop Title Here” area in the Form Editor.

Drag on a label for the title

Give it the text ‘BookFinder’.

Step 2: Add a Button

Drag a new Button onto the Form:

Drag on a fresh button

Give it the primary-color role and the text “Random Book”.

Step 3: Add author labels

Drag two Labels onto the Form in the Form Editor:

Drag two new labels on

Give one the name book_title and the other the name book_author. In the text options, give them both the center align and make book_title bold:

Drag two new labels on

Step 4: Write the code behind the button

Now we’re going to give our ‘Random Book’ button something to do. Double-click the button in the Design panel. This will open a new function in the Code view that we can fill with our chosen Python code.

Double click the button to create the new function

Add these lines of code to the function:

def button_1_click(self, **event_args):
    """This method is called when the button is clicked"""
    self.button_1.text = "Another book?"
    r = choice(self.worksheet.rows)
    self.book_title.text = r['Title']
    if r['Authors']:
      self.book_author.text = f"by {r['Authors']}"
      self.book_author.text = ""

Make sure you remember to import choice at the top of your code, so that the function can use it.

from random import choice

Step 5: Try it out

Now every time a user clicks the button in your app, your code will find and display a random book title and the corresponding author from your Google Sheet.

Example of what happens when we click the button

Press ‘Run’ to try it out yourself!

Now we have displayed book data from the Google Sheet at the press of a button. Nice job!

In Chapter 3, we’ll add some cover images from OpenLibrary.

Chapter complete

Congratulations, you've completed this chapter!