我正在尝试创建一个与RS232串行对象通信的GUI。我将针对我所面临的问题提出类似的情景。我想用2个按钮创建一个框架,Start和Stop。开始按钮调用'foo'功能:
status = True
def foo():
n = 0
while(getStatus()):
print n
n += 1
sleep(0)
这个foo功能一直运行,直到我按下停止。
def getStatus():
return status
def stop():
status = False
我知道Tkinter是单线程的,一旦我按下“开始”,GUI就会冻结。我知道after
函数可以实现这一点,但我非常想使用线程。这可能与线程有关吗?如果是这样,请提供示例代码?谢谢。
答案 0 :(得分:1)
这里有一些(还不完美的)代码:
什么遗失/坏了,但你没有要求这个,我添加了链接:
同样用于停止线程看here
import time
import tkinter
from tkinter import ttk
import threading
#gui
root = tkinter.Tk()
root.title("Threading demo")
status = tkinter.StringVar()
elapsed = tkinter.StringVar()
error = tkinter.StringVar()
#thread
class timer(threading.Thread):
def __init__(self):
super().__init__()
self.stopped = False
#your code here, don't need init if you have no code
def run(self):
status.set('running')
while not self.isStopped():
time.sleep(1)
try:
oldtime = int(elapsed.get())
except ValueError:
oldtime = 0
elapsed.set(oldtime+1)
status.set('stopped')
time.sleep(2)
def isStopped(self):
return self.stopped
def stop(self):
self.stopped = True
#starts/stops thread (manages it)
class threadedOp(object):
def __init__(self):
self.thread = None
def run(self):
if self.thread == None:
self.thread = timer()
status.set('starting')
self.thread.start()
else:
error.set('Thread already running')
def stop(self):
if self.thread != None:
status.set('stopping')
self.thread.stop()
self.thread.join()
error.set('Join complete')
self.thread = None
else:
error.set('No thread to stop')
op = threadedOp()
#remaining gui
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(tkinter.N, tkinter.W, tkinter.E, tkinter.S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)
ttk.Label(mainframe, textvariable=elapsed).grid(column=1, row=1, sticky=(tkinter.W, tkinter.E))
ttk.Label(mainframe, textvariable=status).grid(column=2, row=1, sticky=(tkinter.W, tkinter.E))
ttk.Label(mainframe, textvariable=error).grid(column=1, row=3, sticky=(tkinter.W, tkinter.E))
ttk.Button(mainframe, text="Start", command=op.run).grid(column=1, row=2, sticky=tkinter.W)
ttk.Button(mainframe, text="Stop", command=op.stop).grid(column=2, row=2, sticky=tkinter.W)
root.mainloop()