I am trying to build a following kivy app:
- Select a folder on screen one
- Popup window comes up showing progress of populating a list of dictionaries with files info from selected folder
- Once this is done, pop up closes, app switches automatically to screen 2
- screen 2 will display files of the directory (using RecycleView)
this is where I am:
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.filechooser import FileChooserListView
from kivy.properties import StringProperty, ObjectProperty, ListProperty
from kivy.graphics import Color, Rectangle, RoundedRectangle
from kivy.clock import Clock
from kivy.uix.popup import Popup
from kivy.uix.progressbar import ProgressBar
from kivy.uix.recycleview import RecycleView
from kivy.uix.recycleview.views import RecycleDataViewBehavior
# from logic import analyze_directory
import os
from threading import Thread
import time
import sys
file_list = [{'file': 'a', 'path': 'c/ddd'},
{'file': 'b', 'path': 'c..d'}]
class RoundedButton(Button):
def __init__(self, **kwargs):
super(RoundedButton, self).__init__(**kwargs)
self.background_normal = '' # Disable the default background
self.background_color = (0, 0, 0, 0) # Make the background transparent
self.color_normal = (0.2, 0.6, 1, .8) # Normal color
self.color_down = (0.1, 0.3, 0.43, 1) # Color when pressed
with self.canvas.before:
self.color_instruction = Color(*self.color_normal)
self.rect = RoundedRectangle(size=self.size, pos=self.pos, radius=[20])
self.bind(pos=self.update_rect, size=self.update_rect)
self.bind(on_press=self.on_button_press, on_release=self.on_button_release)
def update_rect(self, *args):
self.rect.pos = self.pos
self.rect.size = self.size
def on_button_press(self, *args):
self.color_instruction.rgba = self.color_down
def on_button_release(self, *args):
self.color_instruction.rgba = self.color_normal
class FileChooser(FileChooserListView):
def __init__(self, **kwargs):
super().__init__(**kwargs)
class IntroScreen(Screen):
pass
class DrivesLayout(BoxLayout):
drive_buttons = []
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.spacing = "3dp"
self.size_hint_y = 0.17
drives = self.get_available_drives()
for index, drive in enumerate(drives):
drive_button = Button(text=drive, size_hint=(None, None), size=(30, 30), background_normal="",background_color=(0.1,0.1,0.1,1))
drive_button.bind(on_press=lambda instance, drive=drive: self.select_drive(drive))
self.add_widget(drive_button)
self.drive_buttons.append(drive_button)
if index == 0: # Highlight the first drive button
drive_button.background_normal = ""
drive_button.background_color = (0, 0.5, 0,1)
def get_available_drives(self):
drives = []
drive_buttons = []
if os.name == 'nt': # Windows
import win32api
bitmask = win32api.GetLogicalDrives()
for letter in range(65, 91):
if bitmask & 1:
drives.append(chr(letter) + ":/")
bitmask >>= 1
else: # Unix/Linux/MacOS
drives = [os.path.join('/', d) for d in os.listdir('/') if os.path.isdir(os.path.join('/', d))]
return drives
def select_drive(self, drive):
for button in self.drive_buttons:
button.background_color = (0.1,0.1,0.1,1) # Reset background color of all buttons
button.spacing ="30dp"
# print(DirectorySelectorScreen.ids.file_chooser)
app = App.get_running_app()
app.root.get_screen("dirsel").ids.file_chooser.path = drive
self.drive_buttons[self.get_available_drives().index(drive)].background_normal = "" # removes grey background (otherwise artifact white dots)
self.drive_buttons[self.get_available_drives().index(drive)].background_color = (0, 0.5, 0,1 ) # Highlight selected button
class DirectorySelectorScreen(Screen):
def __init__(self, **kw):
super().__init__(**kw)
label_text = StringProperty('Select a Directory to be checked for duplicate files:')
# def on_kv_post(self, base_widget):
# # This method is called after the widget is fully initialized
# self.label_text = self.ids.file_chooser.path
def get_current_path(self):
return self.ids.file_chooser.path
def selection_to_label(self):
if self.ids.file_chooser.selection[0]:
self.label_text = self.ids.file_chooser.selection[0]
else:
self.label_text = self.ids.file_chooser.path
def submit_path(self):
dir_path = ''
if self.ids.file_chooser.selection:
self.label_text = self.ids.file_chooser.selection[0]
self.ids.file_chooser.selection = []
dir_path = self.label_text
else:
self.label_text = self.ids.file_chooser.path
dir_path = self.label_text # path for the logic
# print(dir_path)
self.manager.current = 'results'
self.show_popup(dir_path)
def show_popup(self, dir_path):
# Create the popup layout
popup_layout = BoxLayout(orientation='vertical', padding=10, spacing=10)
self.progress_bar = ProgressBar(max=100)
self.progress_label = Label(text='Progress: 0%')
popup_layout.add_widget(self.progress_label)
popup_layout.add_widget(self.progress_bar)
# Create the popup window
self.popup = Popup(title='Analyzing Directory '+ dir_path,
content=popup_layout,
size_hint=(0.8, 0.4))
self.popup.open()
# Start the directory analysis in a separate thread
Thread(target=self.analyze_directory, args=(dir_path,)).start()
def update_progress(self, progress):
self.progress_bar.value = progress
self.progress_label.text = f'Progress: {int(progress)}%'
# Ensure UI updates are handled in the main thread
App.get_running_app().root.do_layout()
def analyze_directory(self, path):
global file_list
try:
# faster way to count files for progress bar but problem with permissions
total_files = count_files_in_directory(path)
except:
# backup way of counting the files for the progress bar
total_files = sum([len(files) for r, d, files in os.walk(path)])
files_processed = 0
for root, dirs, files in os.walk(path):
for file in files:
file_info = {}
file_path = os.path.join(root, file)
file_size = os.path.getsize(file_path)
file_creation_date = os.path.getctime(file_path)
file_info = {
'file': file,
'size': file_size,
'created': file_creation_date,
'path': file_path
}
file_list.append(file_info)
# Update progress
files_processed += 1
progress = (files_processed / total_files) * 100
self.update_progress(progress)
print(total_files)
print(f'print from end of analyze_dir: {file_list}')
self.update_progress(100) # Ensure the progress bar reaches 100%
time.sleep(1)
self.popup.dismiss() # Close the popup after completion
ResultsScreen.data = file_list
# You can further process `file_list` as needed
def count_files_in_directory(self, path):
pass
def count_files_in_directory(path):
file_count = 0
with os.scandir(path) as entries:
for entry in entries:
if entry.is_file():
file_count += 1
elif entry.is_dir():
file_count += count_files_in_directory(entry.path)
return file_count
class recycleView(RecycleView):
pass
class ResultsScreen(RecycleDataViewBehavior,Screen):
global file_list
data = ListProperty()
recycleView = ObjectProperty(None)
data = file_list
# print(data)
def refresh_view(self):
global file_list
print(f'printing from refresh_view before refresh: {self.recycleView.data}')
self.ids.recycleView.data = []
self.ids.recycleView.data = file_list
print(f'this should be updated filelist from refresh_view: {file_list}')
self.ids.recycleView.refresh_from_data()
class ItemWidget(BoxLayout):
file = StringProperty()
path = StringProperty()
class MyScreenManager(ScreenManager):
pass
class GruntleDuplicateFileRemoverApp(App):
pass
GruntleDuplicateFileRemoverApp().run()
and the .kv.file:
MyScreenManager:
DirectorySelectorScreen:
ResultsScreen:
IntroScreen:
<IntroScreen>:
name: "intro"
Button:
text: 'intro screen'
<ResultsScreen>:
on_pre_enter: root.refresh_view()
recycleView: recycleView
name: "results"
RecycleView:
id: recycleView
data: root.data
viewclass: 'ItemWidget'
RecycleBoxLayout:
default_size: None, dp(80)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
# spacing: dp(5)
<ItemWidget>:
Label:
text: root.file
<Drives>:
size_hint_y: 0.2
<DirectorySelectorScreen>:
name: "dirsel"
BoxLayout:
orientation: "vertical"
Label:
id: path_label
text: root.label_text
font_size: "25dp"
size_hint_y: None
padding: dp(10), dp(30), dp(10), dp(20)
text_size: self.width, None
halign: 'center'
height: self.texture_size[1]
DrivesLayout:
# Button:
# on_press: root.do_something()
BoxLayout:
FileChooserListView:
id: file_chooser
dirselect: True
show_hidden: False
AnchorLayout:
size_hint_y: 0.2
RoundedButton:
text: 'select'
size_hint: None, None
size:(dp(100), dp(40))
on_release: root.submit_path()
The Problem I have is that the screen 2 is not showing the populated files, but only default dummy data (which i hardcoded in order to see that RecycleView is loading data from designated global variable). With the help of print statements in various places I can see that the global variable file_list is updated with the files-info, but I don’t know how to make the RecycleView update to reflect new data.
Please help!
I have tried to Implement refresh_view function, that has got refresh_from_data() in it, but it doesn’t work.
I suspect the refresh_view() is called before the list is populated, perhaps because the data is collected in analyze_dir() function that is run in new thread due to need of not blocking the main thread so that the progress bar is showing correctly…?
Thanks for any help!
user23484922 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.