Я собрал GUI, который в течение некоторого времени ищет конкретную c тему в вашем письме l oop и продолжает это делать, пока не найдет непрочитанное сообщение с этой темой. Как только он находит это электронное письмо, он выполняет некоторые другие функции, а когда все эти функции завершены, он возвращается к началу и снова ищет непрочитанное сообщение, содержащее эту тему. Я хочу реализовать кнопку «стоп», которая позволит пользователю вырваться из этого бесконечного l oop поиска в папке «Входящие», но я не добился успеха и не уверен, как решить эту проблему. Я пытался найти сопоставимые примеры, но не смог реализовать их в моей конкретной ситуации c. Я укоротил код настолько, насколько это было возможно, чтобы все еще интерпретировать.
class App(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.desktop_path = os.path.join(os.environ['USERPROFILE'],'Desktop')
#create labelframe for directory and browse button
label_frame = tk.LabelFrame(self, text=" Search Inbox:")
label_frame.grid(row=1, columnspan=15, sticky='WE', padx=5, pady=5, ipadx=5, ipady=5)
#create label frame for send report and button
label_frame2 = tk.LabelFrame(self, text=" Interrupt Search:")
label_frame2.grid(row=2, columnspan=15, sticky='WE', padx=5, pady=5, ipadx=5, ipady=5)
#create label frame for send report and button
self.label_frame3 = tk.LabelFrame(self, text=" Totals:")
self.label_frame3.grid(row=3, columnspan=15, sticky='WE', padx=5, pady=5, ipadx=5, ipady=5)
#create browse button and place on grid
label_frame.button = ttk.Button(label_frame, text="Start",command=self.start, width=8)
label_frame.button.grid(row=4, column=7, sticky="EW", padx=100, ipadx=10)
#create send report button and place on grid
label_frame2.button = ttk.Button(label_frame2, text='Stop', command=self.stop, width=8)
label_frame2.button.grid(row=4, column=7, sticky='EW', padx=100, ipadx=10)
self.label_frame3.entry = tk.Entry(self.label_frame3)
self.label_frame3.entry.grid(row=4, column=7, stick='W', padx=50, ipadx=25)
def SaveAttachments(self, subject='subject matter goes here'):
#create outlook application object
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6) #create an inbox object
messages = inbox.Items #create a message object
try:
inbox.Folders.Add('Extracts') #create folder in inbox, if already exsists, nothing happens.
except:
pass
#iterate through messages to find message that matches subject and is unread
for message in messages:
if message.Subject == subject and message.Unread:
attachments = message.Attachments
attachment = attachments.Item(1)
for attachment in message.Attachments:
if not os.path.isdir(self.desktop_path): #check if the path exsists, and if it doesn't, create it
os.makedirs(self.desktop_path)
attachment.SaveAsFile(os.path.join(self.desktop_path, str(attachment)))
if message.Subject == subject and message.Unread:
message.Unread = False #change message status from unread to read
message.Move(inbox.Folders('Extracts')) #move read messages to Extracts Folder
#print(attachment)
break
else:
attachment = None
return os.path.join(self.desktop_path, str(attachment))
def start(self, event=None):
self.cancel_id = None
self.main()
def main(self, event=None):
variable = True
while variable:
file = self.SaveAttachments()
if 'None' not in file:
variable = False
self.CreatePivots(file)
self.CreateExcel()
self.SendEmail()
self.label_frame3.entry.delete(0, 'end')
self.label_frame3.entry.insert(0, f'{self.table.iloc[-1,0]}')
self.cancel_id = self.label_frame3.entry.after(1000, self.main)
variable = True
def stop(self, event=None):
if self.cancel_id is not None:
self.label_frame3.entry.after_cancel(self.cancel_id)
self.cancel_id = None