【问题标题】:How to stop or interrupt a function in python 3 with Tkinter如何使用 Tkinter 在 python 3 中停止或中断函数
【发布时间】:2016-10-14 10:54:34
【问题描述】:

几个月前我开始使用 python 编程,我真的很喜欢它。 一开始就非常直观和有趣。

起点数据: 我有一个运行 python 3.2.3 的 linux mashine 我在 GUI 上有三个按钮来启动一个函数,一个按钮来停止该进程或进程(想法)。

来源如下:

def printName1(event):
    while button5 != True
    print('Button 1 is pressed')
    time.sleep(3) # just for simulation purposes to get reaction time for stopping

    return
print('STOP button is pressed')

def StopButton():
    button5 = True

我尝试过while,并尝试使用except,但主要问题是GUI(thinter)在进程运行期间当时没有响应。它存储输入并在第一个函数 (printName1) 完成后运行它。 我也在这里查看了stackoverflow,但解决方案对我来说不能正常工作,而且他们在中断方面也有同样的问题。 我为那个(也许)基本问题道歉,但我在 python 中很新,花了几天时间搜索尝试。

有没有办法做到这一点?解决方案可以用线程来解决吗?但是怎么做? 非常感谢任何建议/帮助。

非常感谢!

【问题讨论】:

  • 是的,您需要将该函数放入不同的线程中。与 GUI 在同一线程上运行的所有内容都会阻止它并阻止任何输入。 (在某些情况下,您也可以使用生成器函数来做到这一点,但一般来说线程是“必经之路”)
  • 好的,非常感谢布莱恩。那么我如何从该功能开始或更具体地如何使用该线程终止功能。我不知道或不理解这将如何工作或看起来像。我可以用非常简单的语法来想象,但这似乎是有线的还是不是很明显?
  • 您有几种不同的选择。对于这种情况,最简单的可能是将printName1 的整个功能移动到一个线程中。该解决方案可能并不适合所有问题,但它适用于这个问题。 Python 本身提供了一些不同的库来处理并行性,包括concurrent.futurethreading_thread

标签: python tkinter


【解决方案1】:

使用threading.Event

import threading
class ButtonHandler(threading.Thread):
    def __init__(self, event):
        threading.Thread.__init__(self)
        self.event = event
    def run (self):
        while not self.event.is_set():
            print("Button 1 is pressed!")
            time.sleep(3)
        print("Button stop")

myEvent = threading.Event()

#The start button
Button(root,text="start",command=lambda: ButtonHandler(myEvent).start()).pack()



#Say this is the exit button
Button(root, text="stop",command=lambda: myEvent.set()).pack()

【讨论】:

  • 感谢 Dashadower 的回复和代码。我发现这有“_initilizing”错误。我可以通过添加以下行 threading.Thread.__init__(self) 来修复它,但它并没有停止进程,在它停止后,我需要从头开始运行程序。我无法再次运行该程序。我的想法是按我的意愿多次按下button1,但可以随时停止线程,而不是让它从头开始运行而不重新启动整个程序。
  • @skyflyofsw 感谢您解决这个问题,我编辑了我的答案。另外,你的意思是如果你按下停止按钮,线程就不会停止?
【解决方案2】:

另外,您可能想看看使用 Tk.after。我发现它比线程更容易和更直观。 after 命令以毫秒为单位等待时间,然后在该时间之后运行命令。

def printName1():
    if button5 != True:
        print('Button 1 is pressed')
    else:
        print('STOP button is pressed')
    root.after(1000,printName1)

def stopButton():
    button5 = True

root = Tk()
app = Frame(root)
app.pack()

stopbtn = Button(app, text='STOP', command=stopButton)
stopbtn.pack()

root.after(1000,printName1)
root.mainloop()

也许这个答案也会有所帮助:How do you create a Tkinter GUI stop button to break an infinite loop?

【讨论】:

    猜你喜欢
    • 2020-01-09
    • 2012-04-04
    • 2019-05-24
    • 1970-01-01
    • 2020-05-28
    • 2020-02-16
    • 2022-01-21
    • 1970-01-01
    • 2012-01-11
    相关资源
    最近更新 更多