2017-04-06 69 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

相關問題