【问题标题】:Threading in Python SugggestionsPython 中的线程建议
【发布时间】:2017-12-31 22:00:57
【问题描述】:

我目前正在尝试在 python 中创建两个循环。目前一个是 tkinter 循环,显示我设置的 gui,另一个是 p2p 聊天功能。使用“导入线程”,定义线程并单独启动它们似乎不起作用。对于我可以使用什么方法让这两个循环同时运行有什么建议吗?

我用来启动线程的代码:

thread1 = threading.Thread(target=x.mainloop())
thread1.start()
thread2 = threading.Thread(target=root.mainloop())
thread2.start()

【问题讨论】:

    标签: python multithreading python-3.x


    【解决方案1】:

    您需要传递函数而不调用它们。照原样,您正在尝试调用它们,并将返回值作为线程的target 传递;因为他们永远不会回来,所以你永远不会启动第二个线程。试试:

    thread1 = threading.Thread(target=x.mainloop)  # Removed call parens on target
    thread1.start()
    thread2 = threading.Thread(target=root.mainloop)  # Removed call parens on target
    thread2.start()
    

    【讨论】:

    • 这是问题的一部分,是的,但我也了解到 Tkinter“主要基于单线程事件模型。mainloop()、回调、事件处理程序和引发 tkinter 异常都在单个处理线程。”
    猜你喜欢
    • 2016-03-13
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多