You have a sensor wired to your Raspberry Pi, but want a big digital display of the reading on the screen.
Use the Tkinter library to open a window and write the reading on it as a label with a large font (Figure 12-19).
This example uses data from the ultrasonic rangefinder of Recipe 12.10. So, complete that recipe first if you want to try out this example.
To test out the rangefinder, 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 book’s website, where it is called gui_sensor_reading.py. The code for measuring distances using the ultrasonic sensor is the same as Recipe 12.10, so only the section of the code concerned with displaying the value is repeated here:
class App: def __init__(self, master): self.master = master frame = Frame(master) frame.pack() label = Label(frame, text=’Distance (inches)’, font=(“Helvetica”, 32)) label.grid(row=0) self.reading_label = Label(frame, text=’12.34′, font=(“Helvetica”, 110)) self.reading_label.grid(row=1) self.update_reading() def update_reading(self): cm, inch = get_distance() reading_str = “{:.2f}”.format(inch) self.reading_label.configure(text=reading_str) self.master.after(500, self.update_reading) root = Tk() root.wm_title(‘Range Finder’) |
Discussion
Athough this recipe uses a distance sensor, it would work equally well with the other sensor recipes in this chapter. You just need to change the labels and the method of obtaining a reading from the sensor.
See Also
For information on formatting numbers to a certain number of decimal places, see Recipe 7.1.