In this Kivy Tutorial we are going to learn about FileChooser in Kivy, There are two ready-to-use widgets that provide views of the file system. each of these present the files and folders in a different style. they both provide for scrolling, selection and basic user interaction.
- The
FileChooserListView
displays file entries as text items in a vertical list, where folders can be collapsed and expanded. - The
FileChooserIconView
presents icons and text from left to right, wrapping them as required.
We need to create two files, the first one is our Python file and the second one is our Kivy File, let’s first create the Python file, after creating the file add the following codes in the file, in this code first we have created a class that extends from GridLayout, after that we have created a method in this class, and this method is used for choosing the file in the Kivy FileChooser.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
from kivy.app import App from kivy.uix.gridlayout import GridLayout class MyWidget(GridLayout): def selected(self, filename): try: self.ids.image.source = filename[0] except: pass class FileChooserWindow(App): def build(self): return MyWidget() if __name__ == "__main__": window = FileChooserWindow() window.run() |
Now let’s create our .kv file, i have named my kv file filechooserwindow.kv, make sure that this name should be similar to the main class name, in my case it is FileChooserWindow class. so you can see in the code that we have defined some rules for MyWidget class, because that class extends from the GridLayout and we need to specify the column with id for this GridLayout. after that we have used our FileChooserIconView, as i have already said , there are two types of FileChooser that you can use, the first one is FileChooserListView and the second one is FileChooserIconView. after that we have created our Image, because we want to select an image and add that to our window.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#:kivy 1.10.0 <MyWidget>: cols:2 id:my_widget FileChooserIconView: id:filechooser on_selection:my_widget.selected(filechooser.selection) Image: id:image source:"" |
Run the code and select an image this will be the result.
Also you can use the second type of file chooser, that is FileChooserListView, so we are are going to just bring changes to our kivy file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#:kivy 1.10.0 <MyWidget>: cols:2 id:my_widget FileChooserListView: id:filechooser on_selection:my_widget.selected(filechooser.selection) Image: id:image source:"" |
Run the complete code and this is the result.