-
Well, I am ready to create a file explorer and it's set in ### Textual. =_+
By the way, I have used 'on_list_view_selected', so I can succeed to get the current index of the ListView, and found that I can get the absolute path successfully. How I know, oh well, I debug here. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
Oh, I know 'DirectoryTree', but I have designed the layout and found that tree is not friendly, so 'DirectoryTree' has been given up.
|
Beta Was this translation helpful? Give feedback.
-
The from pathlib import Path
from typing import Any
from textual.app import App, ComposeResult
from textual.widgets import Header, Footer, ListView, ListItem, Label
class FSEntry( ListItem ):
def __init__( self, entry: Path ) -> None:
super().__init__()
self.entry = entry
def compose( self ) -> ComposeResult:
yield Label(
self.entry.stem + ( "/" if self.entry.is_dir() else "" )
)
class FSBrowser( ListView ):
def __init__( self, cwd: Path | None = None, *args: Any, **kwargs: Any ) -> None:
super().__init__( *args, **kwargs )
self._cwd = ( cwd if cwd is not None else Path( "." ) ).resolve()
def on_mount( self ) -> None:
self._refresh()
def _refresh( self ) -> None:
# Clear out anything that's in here right now.
self.clear()
# Now populate with the content of the current working directory. We
# want to be able to go up, so let's make sure there's an entry for
# that...
self.append( FSEntry( Path( ".." ) ) )
# ...and then add everything else we find in the directory.
for entry in self._cwd.iterdir():
self.append( FSEntry( entry ) )
def on_list_view_selected( self, event: ListView.Selected ) -> None:
# If the user selected a directory entry...
if event.item.entry.is_dir():
# ...repopulate with its content.
self._cwd = event.item.entry
self._refresh()
else:
# If it's not a directory then it's a file or some sort of
# file-like entry in the filesystem; handling of that would
# happen here.
pass
class FSBrowserApp( App[ None ] ):
def compose( self ) -> ComposeResult:
yield Header()
yield FSBrowser()
yield Footer()
if __name__ == "__main__":
FSBrowserApp().run() |
Beta Was this translation helpful? Give feedback.
The
ListVIew
has bothclear
andappend
methods, so I'd probably build such a widget around that. By way of illustration, here's how I think I'd approach what you seem to be doing: