2016-07-29 3 views
0

У меня есть функция, которая проверяет каждое указанное пользователем время для обновлений, а если есть, отображать уведомление об этом. Мой код:Вызов wxPython.NotificationMessage в указанное время

def show_notification(): 
    notification_bubble = wx.App() 
    wx.adv.NotificationMessage("", "sample notification").Show() 
    notification_bubble.MainLoop() 

def update(): 
    # retrieve var from newest_porcys_url_imported 
    first_porcys_url = newest_porcys_url_imported() 

    # retrieve var from newest_pitchfork_url_imported 
    first_pitchfork_url = newest_pitchfork_url_imported() 

    # fetch newest review url with get_porcys_review_url 
    get_latest_porcys_url_ = get_porcys_review_url() 
    get_latest_porcys_url = get_latest_porcys_url_[0] 

    # fetch newest review url with get_pitchfork_review_url 
    get_latest_pitchfork_url_ = get_pitchfork_review_url() 
    get_latest_pitchfork_url = get_latest_pitchfork_url_[0] 

    a = first_porcys_url + ' ' + get_latest_porcys_url 
    b = first_pitchfork_url + ' ' + get_latest_pitchfork_url 

    get_datetime = datetime.now() 
    hour = str(get_datetime.hour) 
    minutes = str(get_datetime.minute) 

    f = open('log.txt', 'a') 
    f.write(hour + ':' + minutes + ' ' + a + ' ' + b + '\n') 
    f.close() 
    if first_porcys_url != get_latest_porcys_url or first_pitchfork_url != get_latest_pitchfork_url: 
     print('new reviews') 
     f = open('new reviews.txt', 'a') 
     f.write(hour + ':' + minutes + ' ' + a + ' ' + b + '\n') 
     f.close() 
     return True 
    else: 
     show_notification() 
     return False 

Моя проблема заключается в том, что он отображает только уведомление один раз, и после этого ничего, в том числе выполнение обновления функции не делать. Я заменил call_function() с print инструкция для тестирования и все работало нормально, поэтому вызов этой функции вызывает проблемы.

ответ

1

Проблема заключается в вашей функции show_notification(). Линия:

notification_bubble.MainLoop() 

завершается только после закрытия окна. Итак, что происходит, когда вы вызываете функцию show_notification(), вы заходите в цикл, ожидая закрытия пользователем окна. Но если он это сделает, программа выйдет. Поэтому невозможно вызвать show_notification() более одного раза.

wxPython Documentation on MainLoop()

Я не знаю много о WxPython, но я надеюсь, что вы могли бы получить в резьбе.

Threading Tutorial

Вы бы начать новый поток для каждого уведомления, как это:

import threading 

def show_notification(): 
    notification_bubble = wx.App() 
    wx.adv.NotificationMessage("", "sample notification").Show() 
    notification_bubble.MainLoop() 

def update(): 
    # retrieve var from newest_porcys_url_imported 
    first_porcys_url = newest_porcys_url_imported() 

    # retrieve var from newest_pitchfork_url_imported 
    first_pitchfork_url = newest_pitchfork_url_imported() 

    # fetch newest review url with get_porcys_review_url 
    get_latest_porcys_url_ = get_porcys_review_url() 
    get_latest_porcys_url = get_latest_porcys_url_[0] 

    # fetch newest review url with get_pitchfork_review_url 
    get_latest_pitchfork_url_ = get_pitchfork_review_url() 
    get_latest_pitchfork_url = get_latest_pitchfork_url_[0] 

    a = first_porcys_url + ' ' + get_latest_porcys_url 
    b = first_pitchfork_url + ' ' + get_latest_pitchfork_url 

    get_datetime = datetime.now() 
    hour = str(get_datetime.hour) 
    minutes = str(get_datetime.minute) 

    f = open('log.txt', 'a') 
    f.write(hour + ':' + minutes + ' ' + a + ' ' + b + '\n') 
    f.close() 
    if first_porcys_url != get_latest_porcys_url or first_pitchfork_url != get_latest_pitchfork_url: 
     print('new reviews') 
     f = open('new reviews.txt', 'a') 
     f.write(hour + ':' + minutes + ' ' + a + ' ' + b + '\n') 
     f.close() 
     return True 
    else: 
     notificationThread = threading.Thread(target=show_notification) 
     # Prepare the thread 
     notificationThread.daemon = True 
     # Make shure it will run in the background 
     notificationThread.start() 
     # Start the thread 

     return False 

Таким образом, каждое уведомление является фоновым процессом, в то время как ваша основная программа может продолжать работать.

Я надеюсь, что смогу помочь. Хорошего дня!

1

Вы должны обернуть все это в mainloop:
Это простое приложение создает сообщение блокировки, если вы хотите без блокировки или само сообщение об отмене, то есть совершенно другой коленкор!

import wx 
import time 
def Alerts(x): 
    #Do your stuff here rather than sleeping 
    time.sleep(2) 
    dlg = wx.MessageBox("New Message "+str(x),"My message heading",wx.OK | wx.ICON_INFORMATION) 

if __name__ == "__main__": 
    A1 = wx.App() 
#This could be a while True loop 
    for x in range(10): 
     Alerts(x) 
    A1.MainLoop()