【问题标题】:Basic GUI for shell commands with Python Tk threading and os.system calls带有 Python Tk 线程和 os.system 调用的 shell 命令的基本 GUI
【发布时间】:2011-07-04 20:53:24
【问题描述】:

我正在做一个基本的 GUI,以便在一些 shell 命令之后提供一些用户反馈,真的是一个 shell 脚本的小界面。

显示一个 TK 窗口,等待 os.system 调用完成并在每次 os.system 调用后多次更新 TK 窗口。

线程如何与 tk 一起工作?

就是这样,谢谢!

【问题讨论】:

    标签: python shell command-line tk


    【解决方案1】:

    如果您使用 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,我会去看看!
    • Constantinius 感谢您的输入,我在这里有一个完整的示例:pastebin.com/AD0UAuMS 如果您将其包含在您的答案中,那就太好了。
    【解决方案2】:

    只是我所做的一个基本示例,感谢 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()
    

    【讨论】:

      最近更新 更多