Blog Pages

1/9/18

Raspberry Pi 3 GUI - Part 6A - LED Control Button with Tkinter

Controlling an LED with RPi.GPIO

This program creates a button that accesses the hardware pins on the Raspberry Pi 3 to control an LED. The status of the LED is updated each time the user presses the button.

(1) LED CONTROL CODE
Add this code to your Python 3 editor.

#! /usr/bin/env python

#import Tkinter module, GPIO and atexit
from Tkinter import*
import RPi.GPIO as GPIO
import atexit

# setup GPIO 
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7,GPIO.OUT)

# create window, window title, window size
window = Tk()
window.title( 'tkinter6.PY')
window.geometry('300x200')

# define dynamic properties for led button
def red_led_on():
    GPIO.output(7, True)# set pin 7 to logic "high"
    red_led_status.configure(text='ON')
    button_red_led.configure(command=red_led_off)
    
def red_led_off():
    GPIO.output(7, False)# set pin 7 to logic "low"
    red_led_status.configure(text='OFF')
    button_red_led.configure(command=red_led_on)

def cleanup():
        GPIO.output(7, False);# reset pin 7 to logic low
        GPIO.cleanup()# cleanup GPIO

# create text box 
red_led_status = Label(window, relief='flat',width=4)

# create button
button_red_led = Button(window)

# set button text
button_red_led.configure(text='RED LED',command=red_led_on)

# set status text
red_led_status.configure(text='OFF')                     

# set location of button and text
button_red_led.grid(row=1,column=1,columnspan=1)
red_led_status.grid(row=1,column=2,padx=10)

atexit.register(cleanup)
window.mainloop()


(2) EXAMPLE CODE
My code looks like this:

blizzard tkinter python led control code

(3) SAVE WORK. RUN PROGRAM
Save to your desktop as tkinter6.py
Change directory to your desktop in your terminal editor.
Type chmod 755 tkinter6.py. Press Enter.
Type ./tkinter6.py . Press Enter.

(4) RESULTS - LED "OFF"
Screen Capture of the program window showing button and status text.
Notice that the LED is initially "OFF".



(5) RESULTS - LED  "ON"
Now notice that after pressing the button the LED is "ON". Press the button one more time and the LED will be OFF again.

blizzard tkinter python led control

UP NEXT - HARDWARE HOOKUP - PART 6B

Thanks for reading,
Trenton

No comments:

Post a Comment