1

我想使用 tkinter 为 StackOverflow 创建一个通知系统,当我的收件箱中有未读项目时,我希望它显示通知(但只有一次),它确实如此。但它效率不高。在某些方面它只显示一次通知,当我点击它时,通知需要一些时间才能被 API 识别为已读取,因此新通知不断弹出,导致 GUI 崩溃(因为我在其中运行它一after())。所以我想知道通知部分是否可以通过某种方式提高效率。

代码:

import tkinter as tk
import add
from time import ctime
import datetime
from stackapi import StackAPI
from win10toast import ToastNotifier
import threading
import webbrowser

root = tk.Tk()
root.title('Stack Notifier')

def authorise():
    print('auth')
    global end, acc_key, start, inbox, auth_button
    if required:
        add.run() #selenium for automation
        acc_key = add.acc_key_dum #accesskey passed from another module
        start = datetime.datetime.now()
        hours_added = datetime.timedelta(hours=24)
        end = start + hours_added #time for reaunthentication
        site.key = add.key #access key from another module
        site.access_token = acc_key #access token from another module
        site.max_pages = 1
        inbox = site.fetch('users/13382000/inbox')
        auth_button['state'] = tk.DISABLED
        threading.Thread(target=first).start()
    
    else:
        inbox = site.fetch('users/13382000/inbox')
        threading.Thread(target=first).start()

def first():
    global current, required, inbox, auth_button

    def popup():
        webbrowser.open(link,new=0)

    inbox = site.fetch('users/13382000/inbox')
    print('chc')
    current = datetime.datetime.now()
    if start < current < end:
        required = False
    
    else:
        required = True
        auth_button['state'] = tk.NORMAL 

    if not required:
        print('first')
        is_unread = inbox['items'][0]['is_unread']
        if is_unread:
            title = inbox['items'][0]['title']
            item_type = inbox['items'][0]['item_type']
            link = inbox['items'][0]['link']
            creation_date = ctime(inbox['items'][0]['creation_date'])
            noti = ToastNotifier()
            noti.show_toast(f'StackOveflow - {item_type}',f'{title} - {creation_date}',duration=5,callback_on_click=popup,threaded=True)
            print('yes')
   
    else:
        threading.Thread(target=authorise).start()
    
    root.after(1000,threading.Thread(target=first).start)

required = True #a reference to whether authentication is required again, after 24 hrs
label_login = tk.Label(root,text='Click To authorise with StackOverflow',font=('helvatica',16))
label_login.grid(row=0,columnspan=3)

auth_button = tk.Button(root,text='Authorise',command=authorise)
auth_button.grid(row=1,column=1)

site = StackAPI('stackoverflow')

root.mainloop()

我知道这不是最好的代码,但我对想法和建议持开放态度。

PS:我使用 selenium 进行自动化并要求提供用户凭据。并且它需要每 24 小时给予一次许可,所以我也需要每 24 小时启动一次 selenium,我猜这做得很好。

先谢谢了

4

0 回答 0