Blog Pages

1/17/18

Raspberry Pi 3 GUI - Part 7A - 3 LED Control Buttons with Tkinter

Controlling 3 LED's with Tkinter on Raspberry Pi 3. This code adds some color to the status text so it's easier to tell when the LED's are on.

(1) WINDOW WITH 3 BUTTONS - LED's "ON"




(2) WINDOW - LED's "OFF"




(3) CODE
#! /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)#red led
GPIO.setup(11,GPIO.OUT)#yellow led
GPIO.setup(15,GPIO.OUT)#green led

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

# define dynamic properties for led button
def red_led_on():
    GPIO.output(7, True)
    red_led_status.configure(text='ON',bg='red')
    button_red_led.configure(command=red_led_off)
    
def red_led_off():
    GPIO.output(7, False)
    red_led_status.configure(text='OFF',bg='white')
    button_red_led.configure(command=red_led_on)

def yel_led_on():
    GPIO.output(11, True)
    yel_led_status.configure(text='ON',bg='yellow')
    button_yel_led.configure(command=yel_led_off)

def yel_led_off():
    GPIO.output(11, False)
    yel_led_status.configure(text='OFF',bg='white')
    button_yel_led.configure(command=yel_led_on)

def grn_led_on():
    GPIO.output(15, True)
    grn_led_status.configure(text='ON',bg='green')
    button_grn_led.configure(command=grn_led_off)

def grn_led_off():
    GPIO.output(15, False)
    grn_led_status.configure(text='OFF',bg='white')
    button_grn_led.configure(command=grn_led_on)

def cleanup():
        GPIO.output(7, False)
        GPIO.output(11, False)
        GPIO.output(15, False)
        GPIO.cleanup()

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

# create button
button_red_led = Button(window)
button_yel_led = Button(window)
button_grn_led = Button(window)

# set button text
button_red_led.configure(text='RED LED',command=red_led_on)
button_yel_led.configure(text='YEL LED',command=yel_led_on)
button_grn_led.configure(text='GRN LED',command=grn_led_on)

# set initial status text
red_led_status.configure(text='OFF',bg='white')                     
yel_led_status.configure(text='OFF',bg='white') 
grn_led_status.configure(text='OFF',bg='white') 

# 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)
button_yel_led.grid(row=2,column=1,columnspan=1)
yel_led_status.grid(row=2,column=2,padx=10)
button_grn_led.grid(row=3,column=1,columnspan=1)
grn_led_status.grid(row=3,column=2,padx=10)

atexit.register(cleanup)
window.mainloop()






No comments:

Post a Comment