Kivy:事件定义变量的问题

2024-07-04 17:49:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我对kivy(以及python编程中的面向对象方法)是个十足的noob,我很难实现一个简单的文件检查器(我认为我缺少了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()

我错过了什么?谢谢


Tags: 文件csvpathtextselfinitondef
1条回答
网友
1楼 · 发布于 2024-07-04 17:49:19

通过函数bind,您可以链接一个动作,在您的例子中,这个动作是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()

相关问题 更多 >

    热门问题