在beeware中使用自己的模块

2024-05-16 09:27:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个beeware项目,还想在其中使用我自己的模块,比如模型和控制器。还有一个模块,它创建了一些我可以测试的对象

但是,当我想导入模块来创建测试对象并使用该方法时,它只会抛出一个错误:

ImportError: attempted relative import beyond top-level package

经过一些研究,我知道路径(目录)结构、我把模块放在哪里以及包在哪里都很重要。但无论我把模块放在哪里,它都有相同的(或类似的)错误。但是我可以导入模型来创建这些类的对象。我也不能决定公文包的起点在哪里

以下是我目前的结构:

/Project_Dir (own created)
/briefcase_project (created from briefcase)
/src
  /Models (own created)
  /app_directory (created from briefcase)
      here is the __main__.py and the __init__.py (the start point I guess) and the app.py (where beeware code is, and also my module import from Test)
  /Test (own created, here is a file with a method I want to call)

可悲的是,没有太多关于啤酒的东西可以找到,所以我可以找到一个解决方案

请帮忙。谢谢^^


Tags: 模块andthe对象frompy模型import
2条回答

获取您的项目文件夹名称,然后从那里导入,因此,如果您正在修改教程,并且在与app.py相同的目录中设置了一个名为myModule的模块文件夹,并且有一个名为file.py的文件和一个名为myClass的类,您可以键入:

from helloworld.myModule.file import myClass

为了解决这个问题,我做了以下工作。使用Beeware Tutorial 2源代码的示例位于Github

.
├── __init__.py
├── __main__.py
├── app.py
├── mylib               < - # my lib.
│   ├── __init__.py
│   └── testlib.py
└── resources
    ├── __init__.py
    ├── beewarecustomlibexample.icns
    ├── beewarecustomlibexample.ico
    └── beewarecustomlibexample.png

2 directories, 9 files

{}

def test(text: str) -> str:
    return f"Hello: {text}"

app.py中:

import toga
from toga.style import Pack
from toga.style.pack import COLUMN, ROW

from beewarecustomlibexample.mylib.testlib import test  # Import custom lib


class BeewareCustomLibExample(toga.App):
    def startup(self):

        ...

    def say_hello(self, widget):
        # Calling my test method
        result = test(self.name_input.value)
        self.main_window.info_dialog("Test Dialog", result)


def main():
    return BeewareCustomLibExample()

以上就是我如何让它工作的。我已经在MacOS上构建了它,运行良好

相关问题 更多 >