F
F
Fizl2021-04-01 13:35:36
Python
Fizl, 2021-04-01 13:35:36

How to display the result of a function in a window, parallel to its operation?

Hi all! I need to display the result of a function in a window . It should also run in parallel with the Dialog box . I tried to do this, but all the time only None appeared in the window, instead of the desired result, despite the fact that if you run the function on the command line, separately, it displays a specific result. Here is the DialogMenu( ) class code:def insert_mail(message):DialogMenu( ):

class DialogMenu(tk.Toplevel):
    def __init__(self, user_name):
        super().__init__(root)
        self.user_name = user_name
        self.db = db
        self.get_mail_class_start = get_mail_class_start
        self.db.cur = self.db.conn.cursor()
        self.send_mail = Mail_class(user_name, smtplib.SMTP('smtp.gmail.com:587'))
        self.init_dialog()

    def insert_mail(self, message):
        while True:
            time.sleep(1)
            self.text.insert(tk.INSERT, str(message))

    def retrieve_message_input(self):
        self.text.configure(state = 'normal')
        self.messsage_text = self.Message_Text.get(1.0, tk.END)
        #---self.dialog_file.write(str(self.messsage_text))
        self.text.insert(tk.INSERT, str(self.messsage_text)) 
        #self.text.configure(state = 'disabled')
        self.send_mail.send_mail(self.messsage_text)
        
 
    def init_dialog(self):
        
        self.geometry('600x550')
        self.resizable(False,False)
        self['bg'] = '#2A3132'
        self.minsize(width = 900, height = 550) 
        self.title(f'Диалог с {self.user_name}')
 
        server = 'smtp.gmail.com:587'
        self.send_mail.start_client(server)
        
        #---self.dialog_file = codecs.open(self.user_name[0:-11], 'a+')
        self.dialog_file2 = codecs.open(self.user_name[0:-11], 'r')
        self.Send_btn = tk.Button(self,text = '', padx=15, pady=12.5, font=('Ubuntu',35), 
                                  activeforeground = '#336B87', activebackground = '#2A3132', fg = '#2A3132',
                                  bg = '#336B87',command = partial(self.dialog_db,self.user_name))
 
        self.Send_btn_sms = tk.Button(self,text = '➤',padx = 15,pady = 13,font = ('Ubuntu',35),
                                      bg = '#336B87', command = self.retrieve_message_input, 
                                      activebackground = '#2A3132', fg = '#2A3132', activeforeground = '#336B87')
 
        self.Message_Text = tk.Text(self,width = 45,height = 5,bg='white',fg='black',font = 50)
        self.frame = tk.Frame(self)
        self.text = tk.Text(self.frame, width=85, height=22)
        self.scroll = tk.Scrollbar(self.frame, command=self.text.yview)
        self.scroll.pack(side=tk.RIGHT, fill=tk.Y)
        self.text.config(yscrollcommand=self.scroll.set)
        self.text.insert(tk.INSERT, self.dialog_file2.read())
        #self.text.configure(state = 'disabled')
 
        self.text.pack(side=tk.TOP) 
        self.text.place()
 
        self.frame.pack(side=tk.TOP)
        self.Send_btn.pack()
        self.Send_btn_sms.pack()
        self.Message_Text.pack()
 
        self.Send_btn.place(x = 670,y = 400)
        self.Send_btn_sms.place(x = 545, y = 400)
        self.Message_Text.place(x = 34,y = 400)
 
    def dialog_db(self, user_name):
        DialogDB(user_name)

Here is the code for the function that gives us unread emails:
class get_mail_class():

    def __init__(self, mail, ):
        
        self.mail = mail 
        self.email_file = codecs.open('email.txt', 'r')
        self.password_file = codecs.open('password.txt', 'r')

        self.read_email_file = str(self.email_file.read())
        self.read_password_file = str(self.password_file.read()) 
        (self.retcode, self.capabilities) = self.mail.login(self.read_email_file, self.read_password_file)

    



    def get_mail_func(self):

        my_file = open('text.txt', 'a+')

        self.mail.list()
        self.mail.select('inbox')
        n=0
        (retcode, messages) = self.mail.search(None, '(UNSEEN)')
        if retcode == 'OK':
            for num in messages[0].split():
                n=n+1
                typ, data = self.mail.fetch(num,'(RFC822)')
                for response_part in data:
                    if isinstance(response_part, tuple):
                        original = email.message_from_bytes(response_part[1])
                        raw_email = data[0][1]
                        raw_email_string = raw_email.decode('utf-8')
                        email_message = email.message_from_string(raw_email_string)
                        typ, data = self.mail.store(num,'+FLAGS','\\Seen')

                        if email_message.is_multipart():
                            for payload in email_message.get_payload():
                                
                                body = payload.get_payload(decode=True).decode('utf-8')
                                print(original['From'])
                                print(body)


                                #self.dialog.text.configure(state = 'normal')
                                #self.dialog.text.insert(tk.INSERT, body)
                                #self.dialog.text.configure(state = 'disabled')
                                my_file.write((f"\n {body}"))
                                return body
                        else:
                            
                            body = email_message.get_payload(decode=True).decode('utf-8')
                            print(original['From'])
                            print(body)

                            my_file.write((f"\n {body}"))
                            return body

Here is the last part of the code:
if __name__ == '__main__':

    get_mail_class_start = get_mail_class(imaplib.IMAP4_SSL('imap.gmail.com'))
    root = tk.Tk()
    db = DB()
    

    

    def main_dialog_thread():
        thread_ins = threading.Thread(target = DialogMenu('***************').insert_mail, args = (get_mail_class_start.get_mail_func()), daemon = True) 
        thread_ins.start()

    app = Main(root, '**************')
    app.pack()
    
    def main_mail_thread():
        thread_ma = threading.Thread(target = app.mail_thread, args = (), daemon = True)
        thread_ma.start()

    app.pack()
    root.title('Main')
    root['bg'] = '#2A3132'
    root.geometry('1000x700')
    root.resizable(False,False)


    main_mail_thread()
    main_dialog_thread()
    root.mainloop()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexa2007, 2021-04-01
@Fizl

It is necessary to pass the window object to the class, and then write about the execution process in the methods

from tkinter import *
from time import sleep


class Myfunctions(object):
    def __init__(self, window):
        self.window = window

    def send_email(self):
        self.window.title('Sending message..')
        sleep(2)
        self.window.title('OK')

    def send_email_with_error(self):
        try:
            10/0
        except Exception as e:
            self.window.title('Error sending: '+ str(e))

        
window = Tk() 

helper = Myfunctions(window)
def on():
    helper.send_email()
def off():
    helper.send_email_with_error()


on_btn = Button(window,text='on', height=1, width=20, command=lambda:on()).pack()
off_btn = Button(window,text='off', height=1, width=20, command=lambda:off()).pack()

window.geometry('400x50')
window.resizable(width=False, height=False)

window.mainloop()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question