[英]Python TKinter Threading Help Required
我正在嘗試創建一個與RS232串行對象通信的GUI。 我將針對所面臨的問題提出一個類似的場景。 我想用2個按鈕(開始和停止)創建框架。 開始按鈕調用“ 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
函數實現,但是我嚴格地希望使用threading 。 使用線程有可能嗎? 如果可以,請提供示例代碼? 謝謝。
這是一些(尚未完善)的代碼:
丟失/損壞了什么,但您沒有要求這樣做,我添加了鏈接:
也可以在這里停止線程
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.