Skip to content

Instantly share code, notes, and snippets.

@tshirtman
Last active January 19, 2021 00:21
Show Gist options
  • Save tshirtman/d8423695fe821440b65688b8dbd22b0c to your computer and use it in GitHub Desktop.
Save tshirtman/d8423695fe821440b65688b8dbd22b0c to your computer and use it in GitHub Desktop.
A function to load kv files automatically.
def load_kv():
'''This magical function lookup module name, and load the kv file
with the same name (in the same directory)
'''
filename = inspect.currentframe().f_back.f_code.co_filename
f = extsep.join((splitext(filename)[0], 'kv'))
if exists(f) and f not in Builder.files:
Builder.load_file(f)
@tshirtman
Copy link
Author

example usage.

testclass.py

from utils import load_kv
from kivy.uix.widget import Widget

class Test(Widget):
    pass
load_kv()

testclass.kv

<Test>:
    canvas:
        Rectangle:
            pos: self.pos
            size: self.size

@galou
Copy link

galou commented Jan 29, 2019

Your gist looks like an answer to something I couldn't find in the official Kivy documentation but I couldn't have it run. I get the error

NameError: name 'inspect' is not defined

Thanks for it though.

@tshirtman
Copy link
Author

inspect is a python module, you have to import it.

@pablodz
Copy link

pablodz commented Dec 26, 2019

Interesting

@tafaust
Copy link

tafaust commented Nov 9, 2020

Nice! I am using

import pathlib
Builder.load_file(f'{pathlib.Path(__file__).parent.absolute()}{pathlib.os.sep}{pathlib.Path(__file__).stem}.kv')

in my python files. Works for python 3.7+ AFAIK.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment