kivy

kivy戦記(11) ファイル選択

kivy
この記事は約5分で読めます。

では、ファイル選択してみよう。

kivyでは、FileChooserを使う。

で、そこの公式ドキュメント(https://kivy.org/docs/api-kivy.uix.filechooser.html)のサンプルをまるっとコピーいや、参考にしてみる。

filelist.py


import os
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.popup import Popup
from kivy.uix.treeview import TreeViewLabel
from kivy.properties import ObjectProperty
from pprint import pprint

from kivy.core.text import LabelBase, DEFAULT_FONT
from kivy.resources import resource_add_path
# 日本語フォント設定
resource_add_path('./fonts')
LabelBase.register(DEFAULT_FONT, 'ipaexg.ttf')
class LoadDialog(FloatLayout):
    load = ObjectProperty(None)
    cancel = ObjectProperty(None)
class AllSCN(BoxLayout):
    tv = ObjectProperty(None)
    loadfile = ObjectProperty(None)
    text_input = ObjectProperty(None)
    def __init__(self, **kwargs):
         super(AllSCN, self).__init__(**kwargs)
         self.tv.add_node(TreeViewLabel(text ='シンカリオン E1 とき'))
         self.tv.add_node(TreeViewLabel(text ='シンカリオン 0 ひかり'))
         self.tv.add_node(TreeViewLabel(text ='シンカリオン キハ32 鉄道ホビートレイン'))
    def show_load(self):
        content = LoadDialog(load = self.load, cancel = self.dismiss_popup)
        self._popup = Popup( title="読み込み中", content=content, size_hint=(0.9,0.9))
        self._popup.open()
    def load (self, path, filename):
        pprint(filename)
        #with open (os.path.join(path, filename[0])) as stream:
        #    self.text_input.text = stream.read()
        self.dismiss_popup()
    def dismiss_popup(self):
        self._popup.dismiss()
class FilelistApp(App):
    def build(self):
        return AllSCN()
if __name__ == '__main__':
    FilelistApp().run()

(importは整理しました)

そしてfilelist.kv


<AllSCN>:
    tv: tv
    orientation: 'vertical'
    BoxLayout: #OpnSCN
        size_hint_y: 0.1
        TextInput:
            size_hint_x: 0.8
            text: 'ファイルパス'
        Button:
            size_hint_x: 0.1
            text: '…'
            on_release: root.show_load()
        Button:
            size_hint_x: 0.1
            text: '実行'
    BoxLayout: #ResultSCN
        size_hint_y: 0.9
        TreeView:
            id: tv
<LoadDialog>:
    BoxLayout:
        size: root.size
        pos: root.pos
        orientation: 'vertical'
        FileChooserListView:
            id: filechooser
        BoxLayout:
            size_hint_y : None
            height : 30
            Button:
                text: 'キャンセル'
                on_release: root.cancel()
            Button:
                text: '読み込み'
                on_release: root.load(filechooser.path, filechooser.selection)

AllSCN:

そして起動して、「実行」ボタンを押下。

「・・・」を押下。

フォルダを選択して、

最後にファイルを選択する。その結果、

選択はとりあえず完了。

また粗削りなところがあるけど、とりあえずスムーズに行ったと。

(公式ドキュメントのサンプルのおかげで)

 

 

タイトルとURLをコピーしました