Python Forum

Full Version: Conditional Button Press
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am looking to make a while loop break upon button press but I'm not sure how to do so. I assume it would be with a conditional statement but the syntax is foreign to me.

A pseudocode example would be as follows:

while True:
 - statement
if *Button2 = Pressed*
break

Please help.
What kind of button press? Keyboard in a terminal, or a GUI?

In either case, you'll probably want your loop to execute in a thread that checks a condition that the "presentation" component of your code is able to modify.
Have you tried using an intermediate variable?

I don't know what framework you're using, so here's some pseudopython
class Button:
   def __init__(self):
       self.clicked = False
   def click(self):
       self.clicked = True

btn = Button()
gui_framework.CreateButton().onclick(btn.click)
while not btn.clicked:
   time.sleep(0.1) # so you don't melt your computer :)
This is a tkinter button press. So GUI, a simple Stop button to end the loop. Here is the exact code I am working with.

 
  def callback():
       while True:
           ADC_Value = adc.read_adc_difference(0,gain = GAIN)
           print(ADC_Value, "ADC Value")
           sleep(2)
           x_Input = (((ADC_Value-68)*(1/8002.0))*(1/2.4))-0.25
           print(x_Input, "Current Pressure")
   t = threading.Thread(target = callback)
   t.start()
This would probably solve itself if I could find the tkinter library in my directory.
See: https://python-forum.io/Thread-Music-Notation
There are buttons used in this code. Pay particular attention to the command attribute in tk.Button instances
also and bind statements. These bind the button to to a 'callback'
Note that event is a required argument for determining where the event was created.
To get a list of all possible bindings see: You can bind any key on your keyboard, or mouse clicks.
I wasn't able to find what you were getting at, but I figured out this problem. I made a shutdown function on the module level that changes the value of a global variable from 0 to 1. I added a conditional statement to the while loop that only lets the loop execute if the variable is set to 0. So when I push the start button it sets the variable to 0 and when I push the stop button it sets the variable to 1. After button press the loop breaks and all is well.

Cheers!
buttonname.bind('<Button-1>', ButtonPressedFunction)
buttonname.bind('<ButtonRelease>', ButtonReleasedFunction)
These aren't GUI commands. Thanks anyways!
The hell there not! Look at your tkinter manual
They bind keys and mouse buttons to GUI Button (or other widgets)