如何从FileChooser中选择文件时关闭弹出窗口

时间:2017-03-14 19:12:12

标签: python kivy

当我使用Popup打开FileChooser时,我可以选择一个文件,但我无法在其后关闭Popup。有没有人知道如何在从另一个类引用时关闭Popup

class MyFileChooser(FileChooserListView):

    def on_submit(*args):
        fp=args[1][0]

class MainScreen(BoxLayout):

    def filebtn(self, instance):
        self.popup = Popup(title='Select File',
                      content=MyFileChooser(),
                      size_hint=(None, None), size=(400, 400))
        self.popup.open()

    def __init__(self, **kwargs):
        super(MainScreen, self).__init__(**kwargs)
        self.orientation = 'vertical'
        self.btnfile = Button(text='Open File')
        self.btnfile.bind(on_press=self.filebtn)
        self.add_widget(self.btnfile)

我已经尝试过了

class MyFileChooser(FileChooserListView):
    def on_submit(*args):
        fp=args[1][0]
        popup.dismiss()

但这并不奏效,所以我迷失了方向。任何帮助,将不胜感激。

2 个答案:

答案 0 :(得分:0)

好的,我得到了它我将弹出窗口重新定义为全局,然后我能够从MyFileChooser类中引用它。

def filebtn(self, instance):
        global popup
        popup = Popup(title='Select File',
                      content=MyFileChooser(),
                      size_hint=(None, None), size=(400,400))
        popup.open()

然后在我的MyFileChooser课程中

class MyFileChooser(FileChooserListView):

    def on_submit(*args):
        print(args[1][0])
        global fp
        fp = args[1][0]
        print(fp)
        popup.dismiss()

答案 1 :(得分:0)

Popup似乎可以作为曾祖父访问:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.uix.filechooser import FileChooserListView
from kivy.lang import Builder

Builder.load_string('''
<MyWidget>:
    TabbedPanelItem:
        text: 'tab1'
    TabbedPanelItem:
        text: 'tab2'
''')


class MyFileChooser(FileChooserListView):
    def on_submit(self, *args):
        fp=args[0][0]
        self.parent.parent.parent.dismiss()


class MainScreen(BoxLayout):

    def filebtn(self, instance):
        self.popup = Popup(title='Select File',
                      content=MyFileChooser(),
                      size_hint=(None, None), size=(400, 400))
        self.popup.open()

    def __init__(self, **kwargs):
        super(MainScreen, self).__init__(**kwargs)
        self.orientation = 'vertical'
        self.btnfile = Button(text='Open File')
        self.btnfile.bind(on_press=self.filebtn)
        self.add_widget(self.btnfile)


class MyApp(App):
    def build(self):
        return MainScreen()


if __name__ == '__main__':
    MyApp().run()

当然,如果您以与弹出内容不同的方式使用MyFileChooser类,则此代码将会中断。