< Prev  |  Home  |  Next >

GUIs and Functions

In the last section, we used a callback function to attach a function to a button click. But what if we want a few buttons that all run the same function with different arguments? Imagine a game where the user has to guess which ‘door’ contains a prize. The GUI might look like this:

3 door guessing game GUI

Each of the 3 buttons in this game should run the same function, called ‘checkDoor’, but with different numbers passed to the function as an argument, depending on what button has been pressed. Here’s the program:

If you’ve run this program, you’ll notice that it doesn’t work. As you’ve passed an argument to the ‘checkDoor’ callback function for each button, the program actually calls and runs the function, and then assigns the result to the button, which is not what we want at all.

Instead we need to use the lambda notation to wrap up the function to be called once the button is clicked. It’s done like this:

You may have realised that the name of the variable passed as an argument doesn’t have to match the name of the variable that is the parameter to the function. In the example above, we call:

But the function is defined as:

As the function just takes in whatever value is passed to it, the name of the variable isn’t important, and they certainly don’t have to match. Also, the lambda function can link the variable in the callback function (in this case ‘doorNo’) to the variable for the button number (in this case ‘i’) by using ‘lambda doorNo=i: …’.

Using lambda functions to allow buttons to call functions with parameters means we can write massively interactive GUI programs, and even games such as minesweeper (which is just a 10×10 grid of buttons with a callback function).

Challenge

Develop a ‘Phone Book’ program, that stores the mobile phone numbers and email addresses of a number of contacts. This information could be stored using a dictionary data structure. There is an example of how to use a dictionary to create a phone book here, and details of how to get information out of a dictionary here.

You could then develop a GUI to display the contact details of someone when their button is pressed. It could look like this:

Python phone book program GUI

< Prev  |  Home  |  Next >