0

I am not an experienced programmer. This is probably a simple problem to solve.

I have a function that is supposed to run every two minutes. This function is inside a simple wxPython system tray program. The problem is that I do not know how to run the function because wxPython never leave .MainLoop(). Where should I put the function?

Here is the code: (I have left out the function and import because it is not relevant.)

TRAY_TOOLTIP = 'System Tray Demo'
TRAY_ICON = 'star.png'

def create_menu_item(menu, label, func):
    item = wx.MenuItem(menu, -1, label)
    menu.Bind(wx.EVT_MENU, func, id=item.GetId())
    menu.AppendItem(item)
    return item

class TaskBarIcon(wx.TaskBarIcon):
    def __init__(self):
        super(TaskBarIcon, self).__init__()
        self.set_icon(TRAY_ICON)
        self.Bind(wx.EVT_TASKBAR_LEFT_DOWN, self.on_left_down)
    def CreatePopupMenu(self):
        menu = wx.Menu()
        create_menu_item(menu, 'Say Hello', self.on_hello)
        menu.AppendSeparator()
        create_menu_item(menu, 'Exit', self.on_exit)
        return menu
    def set_icon(self, path):
        icon = wx.IconFromBitmap(wx.Bitmap(path))
        self.SetIcon(icon, TRAY_TOOLTIP)
    def on_left_down(self, event):
        print 'Tray icon was left-clicked.'
        MailCheck()
    def on_hello(self, event):
        print 'Hello, world!'
    def on_exit(self, event):
        wx.CallAfter(self.Destroy)


def main():    
    app = wx.PySimpleApp()
    TaskBarIcon()
    app.MainLoop()

    #This is my function I want to run
    #But MainLoop() never ends. Where should I put MainCheck() ?
    MailCheck()       

if __name__=='__main__':
    main()
4

2 回答 2

1

wxPython 与大多数 GUI 框架一样,使用事件驱动的编程模型。这意味着您的程序的某些部分是响应可能源自用户的操作(例如按键、菜单选择等)系统或可能源自其他程序的操作而运行的。其余时间它位于 MainLoop 中,等待其中一件事情发生。

对于像您这样的情况,有 wx.Timer 类可以触发一次事件,或者可能在 N 毫秒后定期触发。如果您为计时器事件绑定事件处理程序,则该处理程序将在计时器到期时被调用。

于 2013-03-03T21:39:18.253 回答
0

我从未使用过 wxPython,但您可以使用 Python 标准库的 threading-module。

一个最小的例子:

import threading

def work(): 
    threading.Timer(0.25, work).start()
    print "stackoverflow"

work()

看看这个线程(示例来自那里):定期在线程中实时执行函数,每 N 秒

于 2013-03-03T12:15:21.713 回答