繁体   English   中英

在beeware中使用自己的模块

[英]Use own modules in beeware

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

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

ImportError: attempted relative import beyond top-level package

经过一番研究,我知道路径(目录)结构、我的模块所在的位置以及 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)

可悲的是,没有太多关于beeware的东西可以找到,所以我可以找到解决方案。

请帮忙。 谢谢^^

我做了以下工作来解决这个问题。 使用Beeware 教程 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

mylib/testlib.py

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 上构建了它并且工作正常。

取你的项目文件夹名称,然后从那里导入,所以如果你正在修改教程,并且你已经在 app.py 的同一目录中设置了一个名为myModule的模块文件夹,并且你有一个名为app.pyfile.py一个名为myClass的 class ,您可以键入:

from helloworld.myModule.file import myClass

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM