2017-04-06 102 views
0

因此,我有一个程序,它会接收最近的Outlook电子邮件,并在按下按钮时显示它。我想要做的是摆脱按钮,并让answer_label自动运行定时器功能以随时显示电子邮件。有什么建议么?有没有办法让标签在Python Tkinter中运行一个函数?

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

没有标签运行的功能,让按钮运行一次,但有定时器内置到函数,所以它会运行,直到停止它又一个条件语句。 – chbchb55

+0

这实际上是现在它的工作方式。但我想摆脱按钮。我只想让电子邮件在程序打开后自动启动。 – Prox

+0

然后你可以让按钮设置一个变量,告诉程序的另一部分运行该功能并删除该按钮。 – chbchb55

回答

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时要小心。

+0

谢谢。多线程与Tkinter会有什么样的问题? – Prox

+0

@Prox:至少在你的代码中,主线程不在主循环中,应该避免。这里有一些有用的信息:[Link1](http://stackoverflow.com/a/25351697/5520012),[Link2](http://stackoverflow.com/a/14695007/5520012)。 – bqiao