2017-04-24 52 views
-2

我正在使用Python创建一个电子邮件客户端,并且遇到了有关代码格式的轻微问题。我使用的库imaplib和Tkinter的(GUI)在定义它们之前调用Python变量

我有这样的代码片段,显示在列表框中的电子邮件:所以现在我想确定我在这里做lb_leftclick_handler

for i in range(latest_eid, latest_eid-15, -1): 
     i = str (i) #This block of code loads the 15 most recent emails 
     typ, data = mail.fetch(i, '(RFC822)') 

     for response_part in data: 
      if isinstance(response_part, tuple): 
       msg = email.message_from_string(response_part[1].decode('UTF-8'))#Converts the content of the email data to string 
       eSubject = msg['subject']#Variable for the subject of each email 
       eFrom = msg['from']#Variable for the sender of each email 

     eFrom = eFrom.replace('<','') 
     eFrom = eFrom.replace('>','')#Deleting the < & > from the senders email 

     if len(eSubject) > 30: 
      eSubject = eSubject[0:28] + '...' #Load only the first 30 characters of the subject 


     lb = Listbox(rootA) #Listbox to show the emails in the gui 
     lb.pack() 

     lb.insert(END, 'From: (' + eFrom.split()[-1] + ') Subject:' + eSubject) 
     lb.configure(background='black', fg='white', height=2, width=85, font=('Arial', 10)) 
     lb.bind('<Double-Button-1>', lb_leftclick_handler) 

def lb_leftclick_handler(msg): 
    rootB = Tk() 
    rootB.title('Email') 
    rootB.configure(background='black') 
    bodyL = Label(rootB, text='(RFC822)') 
    bodyL.configure(background='black', fg='white') 

基本上我的问题是,我想加载我在第一个代码片段注入我的代码的第二窗口创建窗口解析的电子邮件数据。由于Python是如何格式化的,def lb_leftclick_handler必须在被调用之前放置,但是,我不能将数据加载到窗口中,因为它还不存在。有没有解决方法?如果这个问题的措词很糟糕,我很抱歉。

+0

只需使用类。他们非常甜美,而且很有力量,在班上这些命令等等无关紧要。 –

+0

如果你的代码段出现在一个函数中,只要确保'lb_leftclick_handler'在该函数被调用*之前被定义。如果它不在函数中,那应该是。 – chepner

回答

-1

Python正在解释代码。如果未被调用,它将不执行该功能。您可以安全地将上面的功能代码放在上面,以便在您调用它时定义,当您调用它时,它将获得所需的所有数据。

+0

感谢您的答案,我甚至没有考虑过它可以放在列表框之前,是否有一种方法可以在列表框中选择哪个项目,以便正确的主题/正文可以加载? – Imminence

+0

我从来没有使用过Tkinter。在文档中看到,必须有东西来查看哪一个被检查。 –