Search code examples
pythontkinterimaplib

Calling Python variables before they're defined


I am creating an email client using Python and have run in to a slight issue in regards to the formatting of the code. The libraries I'm using are imaplib and tkinter (gui)

I have this snippet of code which displays the emails in a listbox:

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)

So now I want to define lb_leftclick_handler which I have done here:

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')

Basically my issue is that I want to load the email data I have parsed in the first snippet of code into the window I create in the second window of code. Because of how Python is formatted, def lb_leftclick_handler has to be placed before it is called, however, I then cannot load the data into the window because it doesn't exist yet. Is there a workaround for this? And sorry if the question is worded terribly.


Solution

  • Python is interpreting the code. It will not execute the function if not called. You can safely put the function code above so it will be defined when you call it, and when you call it, it will have all the data it needs.