You want to make an application to run on the Raspberry Pi that has a button for turning things on and off.
Using the Tkinter user interface framework, write a Python program that uses a checkbutton to turn the GPIO pin on and off (Figure 9-8).
You’ll need to connect an LED or some other kind of output device to GPIO pin 18. Using an LED (Recipe 9.1) is the easiest option to start with.
Open an editor (nano or IDLE) and paste in the following code. As with all the program examples in this book, you can also download the program from the Code section of the http://www.raspberrypicookbook.com, where it is called gui_switch.py.
from Tkinter import * import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) class App: def __init__(self, master): frame = Frame(master) frame.pack() self.check_var = BooleanVar() check = Checkbutton(frame, text=’Pin 18′, command=self.update, variable=self.check_var, onvalue=True, offvalue=False) check.grid(row=1) def update(self): GPIO.output(18, self.check_var.get()) root = Tk() root.wm_title(‘On / Off Switch’) app = App(root) root.geometry(“200×50+0+0”) root.mainloop() |
Note that you will need to run it with sudo because the RPi.GPIO requires you to have superuser privileges to access the GPIO hardware:
$ sudo python gui_switch.py |
In Python 3, the Tkinter library has been renamed tkinter with a lowercase t.
Discussion
The example program defines a class called App that contains most of the application code. Its initializer function creates a member variable called check_var that contains an instance of BooleanVar that is then supplied as the variable option to the checkbutton. This ensures that every time the checkbutton is clicked, the value in this variable will be changed. The command option runs the update command every time such a change occurs.
The update function simply writes the value in check_var to the GPIO output.
See Also
You can use this program to control an LED (Recipe 9.1), a high-power DC device (Recipe 9.4), a relay (Recipe 9.5), or high-voltage AC device (Recipe 9.6).