我正在尝试构建以下 kivy 应用程序:
这就是我所在的地方:
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()
和.kv.文件:
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()
我遇到的问题是屏幕 2 没有显示填充的文件,而只显示默认的虚拟数据(我对其进行了硬编码,以便看到 RecycleView 正在从指定的全局变量加载数据)。在各个地方的 print 语句的帮助下,我可以看到全局变量 file_list 已使用 files-info 进行更新,但我不知道如何使 RecycleView 更新以反映新数据。
请帮忙!
我尝试实现refresh_view函数,其中有refresh_from_data(),但它不起作用。 我怀疑在填充列表之前调用了refresh_view(),可能是因为数据是在新线程中运行的analyze_dir()函数中收集的,因为需要不阻塞主线程以便进度条正确显示。 .?
感谢您的帮助!
我认为你需要改变线路:
ResultsScreen.data = file_list
至:
self.manager.get_screen('results').data = file_list
第一个代码将
ListProperty
类中的 list
更改为简单的 ResultsScreen
。第二个将 ListProperty
实例中 ResultsScreen
的值更改为 file_list
。
您还应该删除
ResultsScreen
中的行:
data = file_list
这也取代了
ListProperty
。如果您希望 data
的默认值为 file_list
,您可以将 ListProperty
定义为:
data = ListProperty(file_list)