我正在创建我的第一个 python 包。
在__init__.py
, 我导入并打开一个对象 App
来自模块。
from app import App
app = App()
app.py
:
class App(tk.Tk):
def __init__(self):
#Create App
tk.Tk.__init__(self)
self.geometry("1000x550")
self.title("Game")
self.container = tk.Frame(self).grid()
然后,在另一个模块中game.py
, 我需要访问 app
和 app.container
在 app
时创建在 __init__.py
中初始化.
我试过:
from app import App
# Does not retrieve variables
from __init__ import app
# Does not retrieve object
from app import App
app = App()
# Intialized the object twice
您不应该在 __init__.py
文件中创建 App
的实例。包应该只提供对象的定义。当然也有异常(exception),但刚开始时您不应该这样做。
你的 __init__.py
文件应该只有这个:
from app import App
假设它位于名为“mypackage”的文件夹中,在任何需要应用程序的地方,您都可以:
from mypackage import App
app = App()
我是一名优秀的程序员,十分优秀!