Sunday, March 14, 2021

tkinter python3

Raspberry Pi 

Python3 

Tcl 8.6

26pin GPIO 

GPIO BCM 17,18 and 27


 ## Toggle an LED when the GUI button is pressed ##

# Use only RPi.GPIO to avoid spurious errors

from tkinter import *

import tkinter.font

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)


### HARDWARE DEFINITIONS ###

led0=17

led1=18

led2=27

GPIO.setup(led0,GPIO.OUT)

GPIO.output(led0, False)

GPIO.setup(led1,GPIO.OUT)

GPIO.output(led1, False)

GPIO.setup(led2,GPIO.OUT)

GPIO.output(led2, False)


### GUI DEFINITIONS ###

win = Tk()

win.title("LED Toggler")

myFont = tkinter.font.Font(family = 'Helvetica', size = 12, weight = "bold")



### Event Functions ###

def redledToggle():

    if GPIO.input(led0):

        GPIO.output(led0, False)

        ledButton["text"]="RED on" # Change only the button text property

    else:

        GPIO.output(led0, True)

        ledButton["text"]="RED off"

        

def greenledToggle():

    if GPIO.input(led1):

        GPIO.output(led1, False)

        led1Button["text"]="GREEN on" # Change only the button text property

    else:

        GPIO.output(led1, True)

        led1Button["text"]="GREEN off"


def blueledToggle():

    if GPIO.input(led2):

        GPIO.output(led2, False)

        led2Button["text"]="BLUE on" # Change only the button text property

    else:

        GPIO.output(led2, True)

        led2Button["text"]="BLUE off"

        

def close():

    GPIO.cleanup()

    win.destroy()


### WIDGETS ###


# Button, triggers the connected command when it is pressed

ledButton = Button(win, text='RED on', command=redledToggle, bg='bisque2', height=3, width=24)

ledButton.grid(row=0,column=1)

led1Button = Button(win, text='GREEN on', command=greenledToggle, bg='bisque2', height=3, width=24)

led1Button.grid(row=2,column=1)

led2Button = Button(win, text='BLUE on', command=blueledToggle, bg='bisque2', height=3, width=24)

led2Button.grid(row=4,column=1)


exitButton = Button(win, text='Exit', command=close, bg='red', height=1, width=6)

exitButton.grid(row=6, column=1)


win.protocol("WM_DELETE_WINDOW", close) # cleanup GPIO when user closes window


win.mainloop() # Loops forever


No comments:

Post a Comment