我有一个这样的程序:
from threading import Thread
def foo1(arg):
print("foo1 >>> Something")
input("foo1 >>> Enter Something")
...
def foo2(arg):
print("foo2 >>> Something")
input("foo2 >>> Enter Something")
...
def main():
th1 = Thread(target= foo1)
th1.start()
th2 = Thread(target= foo2)
th2.start()
Run Code Online (Sandbox Code Playgroud)
该程序在同一终端窗口中运行两个函数(foo1和foo2).我可以在某种程度上在不同的终端窗口中运行它们.我不希望的是重新运行该程序.原因是他们在同一个地方同时打印和输入.我不想要.任何方法?
问题是我的解决方案是否是一种使用来自另一个线程的数据更新 Tkinter-GUI 的保存和 pythonic 方式?是Lock必需的吗?或者怎么能在Queue这里提供帮助?此示例运行良好,但原始应用程序需要处理复杂得多的数据。
请专注于AsyncioThread.create_dummy_data()最小的工作示例。该示例有两个线程。一个运行Tkinter -mainloop,第二个线程运行asyncio -loop。异步循环模拟获取一些数据并tkinter.Label用这些数据刷新一些数据。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# restrict to Python3.5 or higher because of asyncio syntax
# based on </sf/answers/3354408991/>
from tkinter import *
import asyncio
import threading
import random
class AsyncioThread(threading.Thread):
def __init__(self, asyncio_loop, theWindow):
self.asyncio_loop = asyncio_loop
self.theWindow = theWindow
self.maxData = len(theWindow.varData)
threading.Thread.__init__(self)
def run(self):
self.asyncio_loop.run_until_complete(self.do_data())
async def do_data(self):
""" Creating and starting 'maxData' asyncio-tasks. """ …Run Code Online (Sandbox Code Playgroud) python asynchronous tkinter python-multithreading python-asyncio