Kivy:事件定义变量的问题



我是一个完全的kivy菜鸟(以及python编程中的面向对象方法),我努力实现一个简单的文件检查器(我认为我错过了kivy逻辑的关键元素)。我希望我的应用指示我的文件是否为 csv

class CsvLoader(BoxLayout):
def __init__(self, **kwargs):
super(CsvLoader, self).__init__(**kwargs)
self.btn = Button(text='Please, Drag and Drop your CSV')
self.add_widget(self.btn)
csv = Window.bind(on_dropfile=self._on_file_drop) # this is the s*** part: how to get the file_path?
if str(csv).split('.')[-1] != "csv'" and csv != None:
self.clear_widgets()
btn_error = Button(text='Wrong file type')
self.add_widget(btn_error)

def _on_file_drop(self, window, file_path):
return file_path

class VisualizeMyCsv(App):
def build(self):
return CsvLoader()
if __name__ == '__main__':
VisualizeMyCsv().run()

我错过了什么?谢谢

使用函数绑定,您可以将一个操作(在您的情况下on_dropfile放置文件时触发的)与触发事件时调用的函数链接,因此必须在该方法中完成逻辑:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.core.window import Window
class CsvLoader(BoxLayout):
def __init__(self, **kwargs):
super(CsvLoader, self).__init__(**kwargs)
self.btn = Button(text='Please, Drag and Drop your CSV')
self.add_widget(self.btn)
Window.bind(on_dropfile=self._on_file_drop)
def _on_file_drop(self, window, file_path):
if str(file_path).split('.')[-1] == "csv'":
print(file_path)
# here you must indicate that it is a .csv file
else:
# it is not a .csv file
print("it is not a .csv file")
class VisualizeMyCsv(App):
def build(self):
return CsvLoader()
if __name__ == '__main__':
VisualizeMyCsv().run()

最新更新