4
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python Kivy で外部KvファイルをIncludeして使用する

Last updated at Posted at 2017-04-09

概要

Includeを使用して外部Kvファイルを取り込む基本的なアプリのテストをしてみました.

環境

  • OS: Windows10 64bit
  • Kivy:1.9.1
  • Python3.5

ポイント

  • 一階層下のフォルダに保存したKvファイルをInclude
  • 外部Kvファイル内のプロパティをRootWidgetのプロパティとして再定義
  • 外部Kvファイル内のon_pressプロパティにRootWidget内のメソッドを関連付け

ファイル配置

project-root
|-- main.py
|-- test.kv
`-- gui/
    `-- tab_test.kv

コードは以下のとおりです.

main.py

main.py
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty

class RootWidget(BoxLayout):
    
    # Kvファイルで定義されている button_include Widget を Pythonファイル内で定義
    button_include = ObjectProperty()  
    
    def print_obj(self, obj):
        print(obj)
        
    def check_button_include(self):
        print(self.button_include)  # Python ファイル内から外部 Kv ファイルのウィジェットクラスにアクセス

class TestApp(App):
    def build(self):
        return RootWidget()


if __name__ == '__main__':
    TestApp().run()

Root Widget を含む Kv ファイル

test.kv
# :include gui/tab_test.kv  # 外部 Kv ファイルを取り込む

<RootWidget>:
    # button_include を RootWidget のプロパティとして定義
    button_include: tab_button_include.button_include

    TabbedPanel:
        do_default_tab: False
        
        TabbedPanelItem:
            text: 'Tab1'
            BoxLayout:
                Button:
                    text: 'button 1'
                    on_press: root.print_obj(self)
                Button:
                    text: 'button 2'
                    on_press: root.check_button_include()
        TabbedPanelItem:
            text: 'Tab2'
            ButtonInclude:  # 外部 Kv ファイルで定義しているウィジェットクラスを使用
                id: tab_button_include  # 定義したウィジェットクラスにid を振っておく

外部 Kv ファイル

tab_test.kv
<ButtonInclude@Button>:
    button_include: button_include

    id: button_include
    text: 'button include'
    on_press: app.root.print_obj(self)  # "app.root.method" で外部Kvファイル内から RootWidget のメソッドを実行

実行結果

kivy_test_include_tab1.png
kivy_test_include_tab2.png

それぞれのボタンの動作結果

Button1          ->   <kivy.uix.button.Button object at 0x000001E0A8DE18D0>
Button2          ->   <kivy.factory.ButtonInclude object at 0x000001E0A8DE1A08>
Button include   ->   <kivy.factory.ButtonInclude object at 0x000001E0A8DE1A08>

参考

4
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?