You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Tkinter GUI与Python异步函数同时运行?

问题:Tkinter GUI与异步函数无法同时运行

我编写了包含CustomTkinter GUI及多个异步函数的Python代码,但运行时两者无法并行:GUI启动后,所有异步函数必须等窗口关闭才会开始执行。

代码片段

# Workers ########################################################################################################

async def process_orders():
    last_incomplete_orders = []
    while True:
        # Logic for order processing here
        #print(colored("Processing orders..."))
        # Get orders that haven't been fulfilled yet
        incomplete_orders = await get_incomplete_orders()
        
        if incomplete_orders != last_incomplete_orders:
            incomplete_order_ids = []
            for payment in incomplete_orders:
                ID, Name, Progress = payment
                incomplete_order_ids.append(ID)
            #print(colored(f'{datetime.datetime.now().strftime("%H:%M:%S")} - IDs of incomplete orders: {str(incomplete_order_ids)[1:-1]}', 'magenta', 'on_white'))
            last_incomplete_orders = incomplete_orders
            
        await asyncio.sleep(5)

async def process_payments():
    last_unconfirmed_payments = []
    while True:
        # Payment processing
        #print(colored("Processing payments..."))

        # Get payments that haven't been confirmed yet
        unconfirmed_payments = await get_pending_payment_requests()
        if unconfirmed_payments != last_unconfirmed_payments:
            printpaymentids = []
            for payment in unconfirmed_payments:
                payment_id, client_id, btc_adress, amt_btc, amt_eur, status = payment
                printpaymentids.append(payment_id)
            #print(colored(f'{datetime.datetime.now().strftime("%H:%M:%S")} - IDs of unpaid payment requests: {str(printpaymentids)[1:-1]}', 'magenta', 'on_cyan'))
            last_unconfirmed_payments = unconfirmed_payments
        for payment in unconfirmed_payments:
            payment_id, client_id, btc_adress, amt_btc, amt_eur, status = payment
            is_confirmed = False 
            is_confirmed = await is_payment_confirmed(payment_id)
            if is_confirmed:
                await release_order(payment_id) 

        await asyncio.sleep(2)  


async def main():
    await clear_all_tables()
    await asyncio.sleep(5)
    task1 = asyncio.create_task(process_orders())
    task2 = asyncio.create_task(process_payments())
    task3 = asyncio.create_task(funfunc())
    task4 = asyncio.create_task(run_gui())
    #task5 = asyncio.create_task(test_product_flow())
    #task6 = asyncio.create_task(test_product_flow())
    #task7 = asyncio.create_task(test_product_flow())
    #task8 = asyncio.create_task(test_product_flow())
    #task9 = asyncio.create_task(test_product_flow())
    #task10 = asyncio.create_task(test_product_flow())

    # Wait for all tasks to complete
    await asyncio.gather(task1, task2, task3, task4)#, task5, task6, task7, task8, task9, task10)


async def funfunc():
    await asyncio.sleep(90)
    messagebox.showinfo('Daily Report', str(await sum_daily_income()))
    
async def run_gui():
    # Create the application window
    window = c.CTk()
    window.title("Simple GUI")
    window.geometry("300x200")

    # Create a label
    label = c.CTkLabel(window, text="Hello, World!")
    label.pack()

    # Create a button
    button = c.CTkButton(window, text="Click me!", command=on_button_click)
    button.pack()
    window.mainloop()


async def create_test_customer():
    await asyncio.sleep(random.randint(1,30))
    await create_client(random.randint(100000,999999), ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(8)))

async def test_product_flow():
    # Create Order
    await asyncio.sleep(random.randint(0,30))
    order_id = await create_order(''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(50)), 100, 'test')
    
    # Create PaymentRequest
    payment_id = await create_payment_request(order_id, 1, 'testbtcadress1827635t123', random.randint(50,1000))
    
    # Confirm or Reject PaymentRequest
    await asyncio.sleep(random.randint(0,30))
    if random.randint(0,1) == 1:
        await confirm_payment(payment_id)
        await asyncio.sleep(random.randint(0,30))
        # Fulfill Order
        await simulate_fulfilled_order(order_id)
    else:
        await reject_payment(payment_id)
        
loop = asyncio.run(main())

已尝试的解决方案

  • 将GUI封装为类,把异步函数设为类方法,但问题仍未解决。

最终解决办法

更新:我通过threading库为GUI和异步函数分别创建独立线程,成功实现了两者并行运行。感谢各位的帮助!


内容的提问来源于stack exchange,提问作者Fabian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 14:07:10