使用Python Tk和os.system调用实现的基本命令行GUI
我正在做一个简单的图形界面,用来在执行一些命令后给用户反馈,实际上就是一个为脚本提供的小界面。
我想显示一个TK窗口,等到一个os.system命令执行完毕后,再多次更新这个TK窗口,每次在os.system命令执行后更新一次。
那请问,线程在tk中是怎么工作的呢?
就这些,谢谢!
2 个回答
1
如果你用Tk来运行程序,标准的线程库应该没问题。这个资料提到,你应该让主线程负责运行图形界面(GUI),然后为你的os.system()
调用创建新的线程。
你可以写一个这样的抽象,完成任务后更新你的图形界面:
def worker_thread(gui, task):
if os.system(str(task)) != 0:
raise Exception("something went wrong")
gui.update("some info")
你可以使用标准库中的thread.start_new_thread(function, args[, kwargs])
来启动线程。详细信息可以在这里找到。
0
这是我做的一个基本示例,感谢Constantinius指出了线程可以和Tk一起使用!
import sys, thread
from Tkinter import *
from os import system as run
from time import sleep
r = Tk()
r.title('Remote Support')
t = StringVar()
t.set('Completing Remote Support Initalisation ')
l = Label(r, textvariable=t).pack()
def quit():
#do cleanup if any
r.destroy()
but = Button(r, text='Stop Remote Support', command=quit)
but.pack(side=LEFT)
def d():
sleep(2)
t.set('Completing Remote Support Initalisation, downloading, please wait ')
run('sleep 5') #test shell command
t.set('Preparing to run download, please wait ')
run('sleep 5')
t.set("OK thanks! Remote Support will now close ")
sleep(2)
quit()
sleep(2)
thread.start_new_thread(d,())
r.mainloop()