Home > Software design >  Image Changes with GPIO pins (ON/OFF)
Image Changes with GPIO pins (ON/OFF)

Time:08-07

I am using gpio pins as input and when any of the pin is high it should show image the problem is when I run the code first time it works fine but when I ON the other pin it is not changing the image while the code is running. The code I am running is given below:

from tkinter import *
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.IN)
GPIO.setup(17,GPIO.IN)
input_state1 = GPIO.input(18)
input_state2 = GPIO.input(17)
while True:
    root=Tk()
    root.geometry('1600x900')
    pix=PhotoImage(file='1.png')
    pic=PhotoImage(file='3.png')
    input_state1 = GPIO.input(18)
    input_state2 = GPIO.input(17)
    if input_state1 == True:
        label_pop = Label(root, image=pix)
        label_pop.grid()

    elif input_state2 == True:
        label_pop1 = Label(root, image=pic)
        label_pop1.grid()       
    root.mainloop()

CodePudding user response:

Since root.mainloop() will not return until root is closed or destroyed, so the first iteration of the while loop will be blocked at the line root.mainloop(). Therefore even there is change on the PIN, no change will be shown or updated.

It is better to run mainloop() only once and don't use while loop in the main thread of tkinter application. For your case, use .after() instead.

import tkinter as tk
from RPi import GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.IN)
GPIO.setup(17,GPIO.IN)

root = tk.Tk()
root.geometry('1600x900')

# assume pix and pic images are loaded somewhere else
#pix = tk.PhotoImage(file='/path/to/pix/image')
#pic = tk.PhotoImage(file='/path/to/pic/image')
blank = tk.PhotoImage()

# create the labels once
label_pop1 = tk.Label(root, width=pix.width(), height=pix.height())
label_pop1.grid(row=0, column=0)

label_pop2 = tk.Label(root, width=pic.width(), height=pic.height())
label_pop2.grid(row=1, column=0)

def check_gpio():
    input_state1 = GPIO.input(18)
    input_state2 = GPIO.input(17)

    # update labels based on reading from PINs
    label_pop1.config(image=pix if input_state1 else blank)
    label_pop2.config(image=pic if input_state2 else blank)

    # call check_gpio one second (1000 ms) later
    root.after(1000, check_gpio)

check_gpio() # start the check loop
root.mainloop()
  • Related