调用app.MainLoop()后更新wxPython进度条

发布于 2024-11-28 01:52:58 字数 354 浏览 0 评论 0原文

我有一个执行计算的 python 脚本,并且我已经为弹出 wxPython 进度条创建了一个类。目前我有:

app=wx.App()
progress = ProgressBar()
app.MainLoop()

for i in xrange(len(toBeAnalysed)):
    analyse(toBeAnalysed[i])
    progress.update(i/len(toBeAnalysed)*100)

现在,这个例子由于明显的原因不起作用。有什么方法可以在不同的线程中运行 app.MainLoop() 但在计算完成时仍然传达进度(和 .update() )?

感谢您的帮助。

I have a python script that performs a calculation, and I have created a class for a pop-up wxPython progress bar. Currently I have:

app=wx.App()
progress = ProgressBar()
app.MainLoop()

for i in xrange(len(toBeAnalysed)):
    analyse(toBeAnalysed[i])
    progress.update(i/len(toBeAnalysed)*100)

Now, this example doesn't work for obvious reasons. Is there any way I can run the app.MainLoop() in a different thread but still communicate the progress (and .update() it) as the calculations are completed?

Thanks for the help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

过去的过去 2024-12-05 01:52:58

您应该在后台线程中运行逻辑并使用 wx.CallAfter 定期更新 GUI。 CallAfter 将在 GUI 线程上调用提供的函数,因此进行 GUI 调用是安全的。

import wx
import threading
import time

def do_stuff(dialog): # put your logic here
    for i in range(101):
        wx.CallAfter(dialog.Update, i)
        time.sleep(0.1)
    wx.CallAfter(dialog.Destroy)

def start(func, *args): # helper method to run a function in another thread
    thread = threading.Thread(target=func, args=args)
    thread.setDaemon(True)
    thread.start()

def main():
    app = wx.PySimpleApp()
    dialog = wx.ProgressDialog('Doing Stuff', 'Please wait...')
    start(do_stuff, dialog)
    dialog.ShowModal()
    app.MainLoop()

if __name__ == '__main__':
    main()

You should run your logic in a background thread and use wx.CallAfter to periodically update the GUI. CallAfter will invoke the provided function on the GUI thread, so it is safe to make GUI calls.

import wx
import threading
import time

def do_stuff(dialog): # put your logic here
    for i in range(101):
        wx.CallAfter(dialog.Update, i)
        time.sleep(0.1)
    wx.CallAfter(dialog.Destroy)

def start(func, *args): # helper method to run a function in another thread
    thread = threading.Thread(target=func, args=args)
    thread.setDaemon(True)
    thread.start()

def main():
    app = wx.PySimpleApp()
    dialog = wx.ProgressDialog('Doing Stuff', 'Please wait...')
    start(do_stuff, dialog)
    dialog.ShowModal()
    app.MainLoop()

if __name__ == '__main__':
    main()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文