以下は、Python 3.12 と Flet 0.28.3 を使用して、ハードコードされたルートディレクトリからそのサブディレクトリと画像を Card として一覧表示し、サブディレクトリに移動したり画像を開いたりできるコードです。また、ルートディレクトリ以外にいるときは戻るボタンで前に戻れる機能と、ルートまで一気に戻るボタンも付けています。Card はレスポンシブに複数列・複数行で表示されます。
import os
import flet as ft
class DirectoryBrowser(ft.UserControl):
def __init__(self, root_dir):
super().__init__()
self.current_dir = root_dir
self.root_dir = root_dir
self.cards_container = ft.GridView(expand=1, runs_count=3, max_extent=200)
self.back_button = ft.ElevatedButton("Back", on_click=self.go_back, visible=False)
self.home_button = ft.ElevatedButton("Home", on_click=self.go_home, visible=False)
self.update_view()
def update_view(self):
self.cards_container.controls.clear()
items = os.listdir(self.current_dir)
for item in items:
item_path = os.path.join(self.current_dir, item)
card = ft.Card(
content=ft.Container(
content=ft.Column([
ft.Text(item),
ft.Image(src=item_path if item.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')) else None)
], alignment=ft.MainAxisAlignment.CENTER, horizontal_alignment=ft.CrossAxisAlignment.CENTER),
padding=10,
),
on_click=lambda e, path=item_path: self.on_card_click(e, path),
)
self.cards_container.controls.append(card)
self.back_button.visible = self.current_dir != self.root_dir
self.home_button.visible = self.current_dir != self.root_dir
self.update()
def on_card_click(self, e, path):
if os.path.isdir(path):
self.current_dir = path
self.update_view()
elif path.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):
os.startfile(path) # Opens the image with the default application
def go_back(self, e):
self.current_dir = os.path.dirname(self.current_dir)
self.update_view()
def go_home(self, e):
self.current_dir = self.root_dir
self.update_view()
def build(self):
return ft.Column(
controls=[
ft.Row([self.back_button, self.home_button]),
self.cards_container,
],
expand=True
)
def main(page: ft.Page):
page.title = "Directory Browser"
root_dir = "/path/to/your/root/directory" # Change this to your root directory
browser = DirectoryBrowser(root_dir)
page.add(browser)
ft.app(target=main)
説明
-
DirectoryBrowser Class:
__init__:
self.current_dir と self.root_dir を初期化。
ft.GridView を使用してカードを複数列で表示。runs_count=3 で3列表示に設定。
- 「Back」と「Home」ボタンを追加。初期状態では非表示。
update_view:
- 現在のディレクトリの内容をリストアップし、カードとして追加。
- サブディレクトリの場合はテキストのみ、画像ファイルの場合はテキストと画像を表示。
- 「Back」と「Home」ボタンの可視性を更新。
on_card_click:
- カードがクリックされた時の処理。ディレクトリの場合はそのディレクトリに移動、画像の場合は画像を開く。
go_back:
- 「Back」ボタンがクリックされた時の処理。1つ前のディレクトリに戻る。
go_home:
- 「Home」ボタンがクリックされた時の処理。ルートディレクトリに戻る。
build:
- UIの構造を定義。ボタンとカードコンテナを含む列を返す。
-
main function:
- Flet アプリのエントリーポイント。
root_dir を適切なパスに変更。
DirectoryBrowser インスタンスを作成し、ページに追加。
注意事項
- root_dir:
/path/to/your/root/directory を実際のルートディレクトリのパスに変更してください。
- os.startfile: このコードはWindowsを想定しています。他のOSでは適切なコマンドに変更する必要があります(例:Macでは
os.system(f'open "{path}"')、Linuxではos.system(f'xdg-open "{path}"'))。