所以我有一个程序可以获取最新的Outlook电子邮件,并在按下按钮后显示它。我想要做的是摆脱按钮,让answer_label自动运行计时器功能,始终显示电子邮件。有什么建议吗?
import win32com.client
import os
import threading # use the Timer
import tkinter
from tkinter import Tk, Label, Button
class myGUI:
def timer(self):
import pythoncom # These 2 lines are here because COM library
pythoncom.CoInitialize() # is not initialized in the new thread
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case,
# the inbox. You can change that number to reference
# any other folder
messages = inbox.Items
message = messages.GetLast()
body_content = message.Body
self.answer_label['text'] = (body_content) # orginally used body_content.encode("utf-8") to fixed character encoding issue
# caused by Windows CMD. But then figured out you can type 'chcp 65001' in cmd
threading.Timer(5, self.timer).start() # refresh rate goes here
def __init__(self, master):
self.master = master
master.title("CheckStat")
self.answer_label = Label(master, text='')
self.answer_label.place(height=300, width=300)
self.greet_button = Button(master, text="Start", command=self.timer)
self.greet_button.place(height=20, width=100)
def greet(self):
print("Greetings!")
root = Tk()
my_gui = myGUI(root)
root.mainloop()
答案 0 :(得分:0)
您不需要显式按钮来运行计时器功能。只需在init中调用它即可。这段代码适合我(它显示时间而不是电子邮件)。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
import threading # use the Timer
from tkinter import Tk, Label, Button
class myGUI:
def timer(self):
self.answer_label['text'] = datetime.datetime.now()
threading.Timer(5, self.timer).start()
def __init__(self, master):
self.master = master
master.title("CheckStat")
self.answer_label = Label(master, text='')
self.answer_label.place(height=300, width=300)
self.timer()
root = Tk()
my_gui = myGUI(root)
root.mainloop()
在多线程应用程序中使用tkinter时要小心。