这段代码工作正常。 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方法?这种分离是明智的吗?任何其他结构建议?
gui.py文件就是这样
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)
将导入添加到myapp.py的顶部,一切都应该正常。
如果有意义的话,我会尝试将我的代码分离成单独的文件。它使阅读事物更加清晰。
在你的gui.py
from myapp import MyApp
class MyGUI(): # displays results from MyApp and sends request to MyApp (e.g. fetch prices new prices)
app = MyApp()
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)
并在您的myapp.py
(请注意第一行),并确保两个文件都在同一目录中,否则您必须相对更改导入。
from gui import MyGUI
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")
最后我做到了这一点 - 似乎是在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 ...