gpt4 book ai didi

python - 如何在不完全退出 Tkinter 窗口的情况下停止正在运行的函数?

转载 作者:行者123 更新时间:2023-12-01 04:37:53 26 4
gpt4 key购买 nike

我正在使用 Python 2.7,并且正在尝试编写 GUI,但我的按钮遇到一些问题。我目前一切正常运行,但假设我的输入或其他内容犯了错误,我想要一种在点击“GO”按钮后停止正在运行的功能的方法。我的代码太长,无法在这里发布,但下面是一个简单的示例。如何使“停止”按钮中断启动功能,但不完全退出窗口?也许与线程有关?

我对编写 GUI 有点陌生,而且我并不是真正的程序员,所以这并不是我的专业领域。

当主函数运行时,GUI 完全没有响应。必须有一种方法可以同时运行我的函数,同时还允许我更改 GUI 中的内容并点击按钮,但我不确定它是如何工作的。不过,直到下次点击“GO”按钮时才需要实现更新。

import time
from Tkinter import *


class Example:
def __init__(self,master):
self.startButton = Button(master,text='Start',command=self.start)
self.startButton.grid(row=0,column=0)

self.stopButton = Button(master,text='Stop',command=self.stop)
self.stopButton.grid(row=0,column=1)

self.textBox = Text(master,bd=2)
self.textBox.grid(row=1,columnspan=2)

def start(self):
self.textBox.delete(0.0,END)
for i in xrange(1000):
text = i+1
self.textBox.insert(END,str(text)+'\n\n')
time.sleep(1)
return

def stop(self):
""" Do something here to stop the running "start" function """
pass


root=Tk()
Example(root)
root.mainloop()

最佳答案

使用Tkinter,这些事情通常使用通用小部件 after() 来完成。方法。通常不应在 Tkinter 程序中使用 time.sleep() ,因为它会阻止 mainloop() 运行(这会导致代码中的 GUI 无响应) .

成功的 after() 调用将返回一个整数“cancel id”,可用于停止刚刚安排的回调。这是 Example 类的 Stop() 方法所需要的,用于停止执行计数的方法。

from Tkinter import *

class Example:
def __init__(self, master):
self.startButton = Button(master,text='Start', command=self.start)
self.startButton.grid(row=0, column=0)

self.stopButton = Button(master, text='Stop', command=self.stop)
self.stopButton.grid(row=0, column=1)

self.textBox = Text(master, bd=2)
self.textBox.grid(row=1, columnspan=2)

def start(self):
self.count = 0
self.cancel_id = None
self.counter()

def counter(self):
self.textBox.delete("1.0", END)
if self.count < 10:
self.count += 1
self.textBox.insert(END, str(self.count)+'\n\n')
self.cancel_id = self.textBox.after(1000, self.counter)

def stop(self):
if self.cancel_id is not None:
self.textBox.after_cancel(self.cancel_id)
self.cancel_id = None

root=Tk()
Example(root)
root.mainloop()

关于python - 如何在不完全退出 Tkinter 窗口的情况下停止正在运行的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31410462/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com