Python Forum

Full Version: tkinter control break a while loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi
I have a basic simple Python 3.5 tkinter program on raspberry pi 3 that runs a stepper motor driven lift.
In the program I have a while loop that generates a square wave that drives the lift to end switches.
The program runs OK from end to end.
I wish to break out of the loop whenever certain button(s) is/are pressed.
My main problem is that the while loop disables the buttons.
If I can get the buttons enabled, I can accept a break command inside the loop.
(I am also unsure about the event.wait(time) that probably runs the same thread, but that's not a problem for now)

What would the right way to resolve and correct my program?
Thanks.
from tkinter import *
root = Tk()
import RPi.GPIO as GPIO
import threading
label = Label(root, text="Lift Control").pack()
GPIO.setwarnings(False)

PUL = 17  # Stepper Drive Pulses
DIR = 27  # Stepper Direction Bit.
ENA = 22  # Stepper Enable
UPSW = 18  # Down end-switch
DNSW = 23  # Up end switch

GPIO.setmode(GPIO.BCM)
GPIO.setup(PUL, GPIO.OUT)
GPIO.setup(DIR, GPIO.OUT)
GPIO.setup(ENA, GPIO.OUT)
GPIO.setup(DNSW, GPIO.IN, pull_up_down=GPIO.PUD_UP)  
GPIO.setup(UPSW, GPIO.IN, pull_up_down=GPIO.PUD_UP)  
pause = 0.001  # For 500 Hz signal
event = threading.Event()

def up():
    dir = 1
    run(dir)
    return

def down():
    dir = 0
    run(dir)
    return

def hold():
    GPIO.output(ENA, GPIO.LOW)
    return

def run(dir):
    switch = UPSW
    if dir == 1:
        GPIO.output(DIR, GPIO.HIGH)
        switch = UPSW
    if dir == 0:
        GPIO.output(DIR, GPIO.LOW)
        switch = DNSW
    GPIO.output(ENA, GPIO.HIGH)
    event = threading.Event()
    
    while GPIO.input(switch) == 0:
        GPIO.output(PUL, GPIO.LOW)
        event.wait(pause)
        GPIO.output(PUL, GPIO.HIGH)
        event.wait(pause)
    GPIO.output(ENA, GPIO.LOW)
    print ('end run')
    return
    
buttonUp = Button(root,text = "to top",width = 15 ,command = up).pack()
buttonDown = Button(root,text = "to bottom",width = 15 ,command = down).pack()
buttonHold = Button(root,text = "Hold",width = 15 ,command = hold).pack()
                  
root.mainloop()