Создать несколько окон tkinter

Всем привет! Возникла такая проблема: хочу создавать нажатием кнопки несколько одинаковых окон tkinter, а вводит уже разные данные для асинхронной работы. Подумал в сторону потоков, но при запуске через поток запускается все равно одно окно, как здесь быть? Заранее благодарен.

Код, который после нажатия кнопки запускается и после его выполнения открывается новое окно tkinter(сначала запускается поток в def auth, после назначается новые loop, а после проходит проверка в async def cli, после в зависимости от результата открывается окно с нужными данными):

    async def cli(self, interval=0.05):
        print(12324)
        #for i in range(1,3):
            #user = 'user' + str(i)
        s = [1, 2, 3, 4, 5, 6]
        client = TelegramClient('q' + str(choice(s)), API_ID, API_HASH)
        try:
            await client.connect()
        except Exception as e:
            print('Failed to connect', e, file=sys.stderr)
            return
        auth = authorisation_account(client)
        try:
            while True:
                auth.update()
                await asyncio.sleep(0.05)
        except KeyboardInterrupt:
            pass
        except tk.TclError as e:
            if 'application has been destroyed' not in e.args[0]:
                raise
        finally:
            await auth.cl.disconnect()
    def run_action(self, user):        
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)   
        
    
    def auth(self):
        clien = self.cli()     
        loop = asyncio.run(clien)
        threads = []
        for i in range(3):
            self.user = 'user' + str(i)
            thread = threading.Thread(target=self.run_action,  name = str(i), daemon= True)
            threads.append(thread)
            thread.start()

Вот код самого окна в tkinter:

class authorisation_account(tk.Toplevel):
        
    def __init__(self, client, *args, **kwargs):
        super().__init__(*args, **kwargs)
        #self.client = TelegramClient(SESSION, API_ID, API_HASH)
        for i in range(1,3):
            self.cl = client
            self.title('Авторизация аккаунтов')
            self.geometry(SIZE)


            self.label = tk.Label(self, text = 'wait a few seconds')
            self.label.grid(row = i, column = 0)

            self.entry = tk.Entry(self,)
            self.entry.grid(row = i, column = 1, sticky = tk.EW)
            self.entry.bind('<Return>', self.sign_in)

            self.button = tk.Button(self, text = '123', command = self.sign_in)
            self.button.grid(row = i, column = 2)

            self.code = None

            self.send_button = tk.Button(self, text = 'send message' + str(i), command = self.send_msg,)
            self.send_button.grid(row = i, column = 3,)
            
            asyncio.create_task(self.post_init())
            


    #async def con(self):
        #await self.client.connect()

    async def post_init(self):
            if await self.cl.is_user_authorized():
                self.set_signed_in(await self.cl.get_me())
                
            else:
                # User is not logged in, configure the button to ask them to login
                self.button.configure(text='Sign in')
                self.label.configure(
                    text='Sign in (phone):')


    @callback
    async def sign_in(self, event = None):
        #for i in range(1,3):
        self.label.configure(text = 'working...')
        self.entry.configure(state=tk.DISABLED)
        if await self.cl.is_user_authorized():
            await self.cl.log_out()
            self.destroy()
            return
        value = self.entry.get().strip()
        if self.code:
            self.set_signed_in(await self.cl.sign_in(code=value))
        #elif ':' in value:
        #    self.set_signed_in(await self.cl.sign_in(bot_token=value))
        else:
            self.code = await self.cl.send_code_request(value)
            self.label.configure(text='Code:')
            self.entry.configure(state=tk.NORMAL)
            self.entry.delete(0, tk.END)
            self.entry.focus()
            return

    def set_signed_in(self, me):
        """
        Configures the application as "signed in" (displays user's
        name and disables the entry to input phone/bot token/code).
        """
        #for i in range(1,3):
        self.me = me
        self.label.configure(text='Signed in')
        self.entry.configure(state=tk.NORMAL)
        self.entry.delete(0, tk.END)
        self.entry.insert(tk.INSERT, utils.get_display_name(me) + ' ' + me.phone )
        self.entry.configure(state=tk.DISABLED)
        self.button.configure(text='Log out')

        #self.chat.focus()

    @callback
    async def send_msg(self, event = None):
        await self.cl.send_message('me', 'hello')

        print('sended')

Ответы (1 шт):

Автор решения: Денис Денис

Нашел такое решение, оказалось все гораздо проще, нужно добавить еще один таск при повторном вызове кнопки.

def auth(self):
        self.n += 1
        clien = self.cli(self.n)
        try:
            loop = asyncio.get_running_loop()
        except RuntimeError:  # 'RuntimeError: There is no current event                                                            loop...'
            loop = None
    
        if loop and loop.is_running():
            print('Async event loop already running. Adding coroutine to the event loop.')
                
            tsk = loop.create_task(clien)
            tsk.add_done_callback(
                lambda t: print(f'Task done with result={t.result()}  << return val of main()'))
        else:
            print('Starting new event loop')
            asyncio.run(clien)
→ Ссылка