0

I'm making a program on python 2.7 with tkinter. This is a simple tkinter GUI with just 1 button, and that button executes a function.

#Code for the tkinter

#function that the button calls
x=0
def check_entry():
    While True:
        try:
            if(x==1):
                #do something
        except KeyboardInterrupt:
            break

This is a example, in reality I'm working with a raspberry pi and what I'm checking (instead of "x") is a GPIO.input.

The problem is that KeyboardInterrupt doesn't work every time. While doing like 30 tests with the code, KeyboardInterrupt worked 2 times (after pressing CTRL-C almost 20 times).

PS1: I'm working en Raspbian.
PS2: I read that maybe the problem is with the interpreter, so I executed the program like an .exe (with chmod +x) and that didn't work.
PS3: I think the problem is that the "Try:" function executes itself many times per second, so the program doesn't catch the pressing of CTRL-C?

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
DJ007
  • 15
  • 4
  • What are you trying to achieve with this function? Why do you need an infinite loop that you break out of? – JohanL Sep 14 '17 at 15:29
  • "doesn't work every time" is unclear, so we can't help you from here. What do you expect? What actually happens when it "doesn't work"? – Thierry Lathuille Sep 14 '17 at 15:29
  • JohanL: I'm trying to check for an entry with 3 modes. mode 1 is going to be an infinite loop (this one), mode 2 is going to be a entry check for 1 day, and mode 3 is going to check for the entry depending on what the user enters. – DJ007 Sep 14 '17 at 15:33
  • Thierry: With "doesn't work every time" I mean that the program keep executing, and only 2 times I was able to close the program. – DJ007 Sep 14 '17 at 15:34
  • It's hard to answer this without seeing a [mcve]. Since it's a very bad practice to have an infinite loop inside of the GUI thread of a tkinter program, there's just no way to give an answer that includes that loop. We can't offer alternatives without knowing more about what you're trying to do with that loop, or why you need to check for a KeyboardInterupt In a GUI program. – Bryan Oakley Sep 14 '17 at 22:15
  • I'm doing a Security cam. So with that entry I check for a PIR entry (through arduino). So the function is: Check the PIR (infinite loop) if the PIR detect something, take a screenshot, and if the PIR doesn't detect anything It need to continue checking until the program its closed. So I though the best way to close this program its through KeyboardInterrumpt. Its there another way? – DJ007 Sep 14 '17 at 23:53

1 Answers1

1

You cannot catch KeyboardInterrupt in Tcl/Tk main loop, it may be handled only by Python interpreter itself. You should use another way to interrupt you program.

Check this answer for additional info.

Roman Mindlin
  • 852
  • 1
  • 8
  • 12