我一直在尝试通过应用程序的按钮释放创建文件选择器弹出窗口。 我分别管理了 FileChooser 和 Popups,但无法将两者一起解决,这里有人可以帮助解决问题吗? 我正在尝试用 Python 而不是 Kivy.lang 来实现 PopUp,因为这是我在弹出窗口方面的经验。我也无法让 Kivy Doc 示例正常工作。 我目前拥有的代码如下。
import kivy
from kivy.uix.filechooser import FileChooserListView
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.uix.popup import Popup
import os
Builder.load_string(
"""
<MyWidget>:
Button
text: "open"
on_release: root.load()
""")
class MyWidget(BoxLayout):
def load(self):
load_popup = Popup(
title = "Select logo",
size_hint = (None, None),
size = (500, 500)
)
file_load= FileChooserListView(
on_selection = self.selected(file_load.selection) #selection not in My
)
content = file_load
load_popup.content = content
load_popup.open()
def open(self, path, filename):
with open(os.path.join(path, filename[0])) as f:
print(f)
def selected(self, filename):
print("selected: %s" % filename[0])
class MyApp(App):
def build(self):
return MyWidget()
if __name__ == '__main__':
MyApp().run()
几乎成功了!问题在于如何将
on_selection
函数传递给
FileChooserListView
以及如何访问所选文件。
无需直接在构造函数中调用
self.selected
,而是在
on_selection
事件发生时将其绑定到调用。Kivy 将为处理这个问题。在
selected
方法内部,可以访问
FileChooserListView
实例的
selection
属性以获取所选文件。
以下是如何修改代码的方法:
import kivy
from kivy.uix.filechooser import FileChooserListView
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.uix.popup import Popup
import os
Builder.load_string(
"""
<MyWidget>:
Button
text: "open"
on_release: root.load()
"""
)
class MyWidget(BoxLayout):
def load(self):
load_popup = Popup(
title="Select logo",
size_hint=(None, None),
size=(500, 500)
)
file_load = FileChooserListView()
# 将 selected 方法绑定到 on_selection 事件
file_load.bind(on_selection=self.selected)
content = file_load
load_popup.content = content
load_popup.open()
def open(self, path, filename):
with open(os.path.join(path, filename[0])) as f:
print(f)
def selected(self, filechooser, filename):
# 通过 filechooser.selection 访问所选文件
print("selected: %s" % filename[0])
class MyApp(App):
def build(self):
return MyWidget()
if __name__ == '__main__':
MyApp().run()
通过这些更改,的文件选择器弹出窗口现在应该可以按预期工作,并允许选择文件并在控制台中打印其路径。
标签:python,kivy,filechooser From: 78796860