【发布时间】:2011-07-04 20:53:24
【问题描述】:
我正在做一个基本的 GUI,以便在一些 shell 命令之后提供一些用户反馈,真的是一个 shell 脚本的小界面。
显示一个 TK 窗口,等待 os.system 调用完成并在每次 os.system 调用后多次更新 TK 窗口。
线程如何与 tk 一起工作?
就是这样,谢谢!
【问题讨论】:
标签: python shell command-line tk
我正在做一个基本的 GUI,以便在一些 shell 命令之后提供一些用户反馈,真的是一个 shell 脚本的小界面。
显示一个 TK 窗口,等待 os.system 调用完成并在每次 os.system 调用后多次更新 TK 窗口。
线程如何与 tk 一起工作?
就是这样,谢谢!
【问题讨论】:
标签: python shell command-line tk
如果您使用 Tk 运行标准线程库,它应该是完全可以的。 This 消息来源说,您应该让主线程运行 gui 并为您的 os.system() 调用创建线程。
您可以编写这样的抽象,在完成任务后更新您的 GUI:
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]) 启动线程。请参阅文档here。
【讨论】:
只是我所做的一个基本示例,感谢 Constantinius 指出 Thread 与 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()
【讨论】: