Scroll Back

Now that we can scroll forward through the records in our database table, we'll add code to scroll back. The code is very similar. Let's add a new function, though. We can rewrite it later to get rid of code duplication.

Add the following function:

def scroll_back:

What we want to do here is to make sure that you can't scroll back before the first record. The first row is row 0. If we are deducting 1 from the row counter every time the back button is clicked it will reach 1, 0, then -1. A value of -1 will cause an error because there won't be a row -1. The program would crash. So we can set up an if statement to check when row_counter reaches 0:

if row_counter is 0:

messagebox.showinfo("Database Error", "Start of database")

Add that to your function and it will look like this in PyCharm:

A Python function to scroll back through database records

If the row_counter is not zero, we can deduct 1 from it in an else part:

if row_counter is 0:

messagebox.showinfo("Database Error", "Start of database")

else:

row_counter = row_counter - 1

When you add that to the code, you should see a red underline in PyCharm. That's because we need to access the global variable row_counter. Add the global at the top of the function:

global row_counter

if row_counter is 0:

messagebox.showinfo("Database Error", "Start of database")

else:

row_counter = row_counter - 1

At this point, you could add the same code as before (but don't). In fact, you could copy and paste the code from your scroll_forward function. Once you add a scroll_back command to your back button, it would work fine. In PyCharm, the two scroll functions would look like this:

Duplicate Python code

However, notice the code duplication here, highlighted above. When you're doing the exact same thing in more than one function, it's a sure sign that you could cut down on your code by setting up a separate function for the duplicated code.

Add a new function. Call it scroll_load_data. Move the highlighted code from scroll_forward into the new function. Call the new function from both else parts. Your code should look like this:

Adding a Python function to cut down on duplictae code

Notice how much cleaner the code looks, now that we've got rid of the duplicated parts from the previous image. Look out for duplication in your programs. It's usually a good idea to clean it up.

Before you can give it a try, locate the back button in your code:

buttonBack = tk.Button(tab1, text="Back")

Add a command parameter and call your scroll_back function.

buttonBack = tk.Button(tab1, text="Back", command=scroll_back)

Now test your program out. You should be able to scroll back and forward through your database records. Try to scroll back past the first record and you should see the error message appear.

And that's it for the All Records tab. We can move on and code for the Add New Record tab.

The Add New Record Tab >