此代码运行正常。 MyApp是完成所有工作的类,而MyGUI是显示和请求MyApp数据的用户界面。
class MyGUI(): # displays results from MyApp and sends request to MyApp (e.g. fetch prices new prices)
def __init__(self):
print("GUI running")
def user_request_price(self,ticker):
self.req_price(ticker)
# methods I request from MyApp
def req_price(self,ticker):
app.get_price(ticker)
# methods I receive from MyApp
def print_price(self,val,price):
print (val,":",price)
class MyApp(): # does a lot of stuff, e.g. fetch prices from a server
def __init__(self):
self.id = 0
self.gui = MyGUI() # start gui
# methods called by GUI
def get_price(self, ticker):
if ticker == "MSFT": price = 20.23
self.output_price(ticker,price)
# methods sent to GUI
def output_price(self,ticker,price):
self.gui.print_price(ticker,price)
if __name__ == "__main__":
app = MyApp()
app.gui.user_request_price("MSFT")
现在,我想将GUI放入一个单独的模块中,因此创建一个模块文件gui.py并将其导入MyApp文件中:
from gui import *
就是这样。我在哪里挣扎:gui.py的外观如何以及MyGUI()如何访问MyApp方法?进行这种分离是否明智?还有其他结构建议吗?
答案 0 :(得分:0)
最后我做到了-似乎是在app和gui之间进行清晰分离和通信的最佳方法。
Gui:
import queue
def __init__(self):
threading.Thread.__init__(self)
self.requests = queue.Queue() # request queue for App
self.start()
def queue_request(self,reqId,val):
self.requests.put([reqId,val])
APP:
import threading
import queue
def checkGUIQueue(self):
threading.Timer(1.0, self.checkGUIQueue).start() # check every 1 second
while not self.gui.requests.empty():
(id,value) = self.gui.requests.get()
... process request ...