문제

I am using tkinter in Python 3 to create a program and I'm stuck... I have infinite loop that is triggered by button press:

def task13():
    while True:
        #do stuff

...

button13 = Button(root, width=25, text="13", command=task13)
goButton.pack(side=LEFT,anchor="n")

How could I terminate task13 on release of the button13? Is there a 'keyboard interrupt' code or can I modify the loop?

도움이 되었습니까?

해결책

There is no way to interrupt a running function. However, you can put a binding on <ButtonRelease-1> for the button, and in that binding you can set a flag. Then, in task13 you can check for that flag at the top of your loop. You will also need a binding on <ButtonPress-1> to start the loop, since the command is tied to the release of the mouse button over the button widget.

This will only work if, while in the loop, you service events. If #do stuff blocks the event loop there's nothing you can do, except to run that code in a separate thread or process.

다른 팁

Button have "<Button-1> and <ButtonRelease-1> events:

from tkinter import *

def press(*args):
    print('press')
    global pressed
    pressed = True
    master.after(0, loop)

def release(*args):
    print('release')
    global pressed
    pressed = False

def loop():
    if pressed:
        print('loop')
        # Infinite loop without delay is bad idea.
        master.after(250, loop)

master = Tk()
pressed = False

b = Button(master, text="OK")
b.bind("<Button-1>", press)
b.bind("<ButtonRelease-1>", release)
b.pack()
mainloop()
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top