2

I have a button that when pressed is supposed to keep printing a certain phrase. However I have an if statement that's supposed to break out of the while loop if it reads that the button is released. Essentially, I'm trying to create a gui that, when a specific button is pressed it continues to act out a function until that button is released in tkinter. I believe that there should be a statement which reads the state of the button and knows when the button is released, but I don't know what it is.

    self.button.pack(side="top")
    self.vsb.pack(side="right", fill="y")
    self.text.pack(side="bottom", fill="x")

    self.button.bind("<ButtonPress>", self.on_press)
    self.button.bind("<ButtonRelease>", self.on_release)

def on_press(self, event):
    while True:
        time.sleep(1)
        self.log("button was pressed")
        if (what do I put here):
            break
Rylan Polster
  • 321
  • 3
  • 14

1 Answers1

0

you can't enter a dead loop while handling an even. try using threads instead.

here is a VERY simple example:

def on_press(self, event):
    self._running = True
    threading.Thread(self.my_loop).start()

def my_loop(self):
    while self.running:
        time.sleep(1)
    print("loop is done")

def on_release(self, event):
    self._running = False # this will stop the loop in the other thread...
Yoav Glazner
  • 7,936
  • 1
  • 19
  • 36