简体   繁体   English

将按钮释放视为键盘中断tkinter

[英]Treat button release as keyboard interrupt tkinter

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: 我在Python 3中使用tkinter来创建一个程序而且我被卡住了...我有无限循环,由按下按钮触发:

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? 如何在发布按钮13时终止task13? 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. 但是,您可以为按钮的<ButtonRelease-1>设置绑定,并在该绑定中设置标志。 Then, in task13 you can check for that flag at the top of your loop. 然后,在task13您可以在循环顶部检查该标志。 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. 您还需要在<ButtonPress-1>上绑定以启动循环,因为该command与按钮小部件上的鼠标按钮的释放相关联。

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. 如果#do stuff阻止事件循环,除了在单独的线程或进程中运行该代码之外,您无能为力。

Button have "<Button-1> and <ButtonRelease-1> events: 按钮有"<Button-1><ButtonRelease-1>事件:

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM