我目前正在使用来自 python 的 tkinter 库处理电子邮件发件人和接收程序。我正在使用线程模块使程序每 60 秒刷新一次未读电子邮件,而您仍然可以继续在程序中执行操作。
线程模块仅在发出 print("something") 命令时工作,我仍然可以继续在程序中做事。但是,当我将线程登录到 gmail 并获取未读电子邮件计数时,整个程序会冻结并崩溃。
下面是我的代码片段。我不会发布完整的代码,我制作了一个简短的版本来展示它的外观。
编辑:在函数中犯了一个小错误。get_credentials() 被删除。
import tkinter, re, threading, time, imaplib, too many to list here.
class Application(Frame):
def __init__(self, parent):
... Start some functions
... Create some widgets
... Create some global stringvars for entry fields
def threadrefresh(self):#I want to start this function when a button is clicked
def multithreading():
usernamevar = "Username"
passwordvar = "Password"
obj = imaplib.IMAP4_SSL('imap.gmail.com', '993') #connect to gmail
obj.login(usernamevar, passwordvar) #log in
obj.select() #select the inbox
unread = str(len(obj.search(None, 'UnSeen')[1][0].split())) #get the total unread
print(unread)
obj.close()
time.sleep(3)
multi = threading.Thread(target=multithreading)
multi.start()
multi = threading.Thread(target=multithreading)
multi.start()
def other_functions_that_do_not_matter_in_this_case():
... Creating GUI
... Sending mail
... Etc.
... Create a button with function call self.threadrefresh
def main():
root = Tk()
app = Application(root)
root.mainloop()
if __name__ == '__main__':
main()