有以下脚本:
import sys, Tkinter
def myScript():
...
...
def runScript():
while 1:
myScript()
我想用Tkinter模块的GUI“按钮”来管理它
if __name__ == '__main__':
win = Frame ()
win.pack ()
Label(win, text='Choose following action', font=("Helvetica", 16), width=70, height=20).pack(side=TOP)
Button(win, text='Start script', width=20, height=3, command=runScript).pack(side=LEFT)
Button(win, text='Stop script', width=20, height=3, command=sys.exit).pack(side=LEFT)
Button(win, text='Quit', width=15, height=2, command=win.quit).pack(side=RIGHT)
mainloop()
当我键入"Start script“按钮时,我的脚本已成功启动并工作(无限循环),但是我想使用”停止脚本“按钮停止执行--我无法这样做,因为带有按钮的主窗口不可用(”没有响应“)
为了正确地使用这两个按钮,我必须更改什么?
发布于 2014-08-21 11:30:20
问题是脚本的执行被认为是阻塞的,因此当脚本持续运行时,该控件永远不会返回到GUI,以便能够继续执行任何外部命令来停止它。要调整这一点,您将需要使用线程。这样做的最佳方法是用threading.Thread
子类您的脚本方法,并用脚本执行重载.run()
方法。这样做的结果如下:
import threading
class MyScript(threading.Thread):
def __init__(self):
super(MyScript, self).__init__()
self.__stop = threading.Event()
def stop(self):
self.__stop.set()
def stopped(self):
return self.__stop.isSet()
def run(self):
while not self.stopped():
# Put your script execution here
print "running"
从这里,您可以设置一个全局变量或类变量,以跟踪当前是否有线程运行(如果您希望用户运行多个脚本实例,您可能希望以不同的方式运行)以及启动和停止它的方法。我推荐一个类变量,您的应用程序本身就是一个类,但这取决于您。
script_thread = None
def startScript():
global script_thread
# If we don't already have a running thread, start a new one
if not script_thread:
script_thread = MyScript()
script_thread.start()
def stopScript():
global script_thread
# If we have one running, stop it
if script_thread:
script_thread.stop()
script_thread = None
在那里,您可以将这些方法绑定到按钮上。我不知道您是如何设置应用程序结构的(在我看来,您从Tkinter或Tkinter.Tk()实例的子类导入了所有东西)。但是,为了执行您的建议,您将需要使用线程来防止阻塞情况。
发布于 2014-08-26 03:09:00
用这个:
import sys
from Tkinter import *
import tkMessageBox as tkmsg
win = None
def myScript():
pass
def runScript():
global win
while 1:
win.update()
pass
def btnStop_Click():
tkmsg.showinfo("Stopped", "Stopped")
sys.exit
if __name__ == '__main__':
global win
win = Frame ()
win.pack ()
Label(win, text='Choose following action', font=("Helvetica", 16), width=70, height=20).pack(side=TOP)
Button(win, text='Start script', width=20, height=3, command=runScript).pack(side=LEFT)
Button(win, text='Stop script', width=20, height=3, command=btnStop_Click).pack(side=LEFT)
Button(win, text='Quit', width=15, height=2, command=win.quit).pack(side=RIGHT)
mainloop()
https://stackoverflow.com/questions/25433819
复制