简体   繁体   中英

Use own modules in beeware

I have a beeware project and also want to use my own modules in it like Models and Controllers. Also, a module which creates some objects I can test with.

But when I want to import the module to create the test objects and use the method it just throws an error:

ImportError: attempted relative import beyond top-level package

After some research, I know that the path (directory) structures, where I put my modules in, and where the package is, are important. But where ever I put the modules it has the same (or kinda like this) errors. But I can import my Models to create objects of these classes. I also can't decide where the start point of the briefcase is.

Here my structure currently:

/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)

Sadly there is not so much stuff to find about beeware so I could find a solution.

Please help. Thanks ^^

I did the following to workaround the issue. The example using the Beeware Tutorial 2 source code is on 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

The mylib/testlib.py

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

In the 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()

The above is how I got it working. I've built it on MacOS and works fine.

Take your project folder name and then import from there, so if you're tinkering with the tutorial and you've set up a module folder called myModule in the same directory as your app.py and you have a file called file.py with a class called myClass , you might type:

from helloworld.myModule.file import myClass

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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