2

我已经阅读了这个问题的许多解决方案,但我仍然无法使这个简单的程序工作。我知道这可能真的很简单,但我不知道我错过了什么。

我有这个简单的程序:

from Tkinter import *
import subprocess

def run():
    process=subprocess.Popen(some_script, shell=True, stdout=subprocess.PIPE)
    while True:
        nextline = process.stdout.readline()
        if not nextline:
            break
        output.set(nextline)
        root.update_idletasks()

root = Tk()
output = StringVar()

label1 = Label(root, textvariable=output)
label1.pack()

button1 = Button(root, text="Go", command=run)
button1.pack()

root.mainloop()

所以当我点击按钮时, some_script 被执行。我希望标签定期更新脚本的输出,但它没有。我究竟做错了什么?

4

1 回答 1

2

我猜当你运行它时 GUI 会变得无响应。如果是这样,那么您正在阻止 Tkinter 的主循环。您需要在线程中运行子进程位并使用 Tkinter 的任何线程安全方法来更新您的 GUI。我发现这篇旧文章听起来与您正在做的非常相似:http: //effbot.org/zone/tkinter-threads.htm

还有这个方便的食谱:http ://code.activestate.com/recipes/82965-threads-tkinter-and-asynchronous-io/

于 2012-06-28T21:46:17.767 回答