这是代码。 TextInput上缺少某些东西。 我创建了一个Filechooser应用程序,它读取文件的内容并在TextInput上打印。只是无法破解最后一部分。
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
import os
Builder.load_string("""
<MyWidget>:
id: my_widget
Button
text: "open"
on_release: my_widget.open(filechooser.path, filechooser.selection)
TextInput:
id: input_text
text: ??????
FileChooserListView:
id: filechooser
on_selection: my_widget.selected(filechooser.selection)
""")
class MyWidget(BoxLayout):
def open(self, path, filename):
with open(os.path.join(path, filename[0])) as f:
print (f.read())
contents=f.read()
MyWidget.input_text.text=contents
def selected(self, filename):
print ("selected: %s" % filename[0])
class MyApp(App):
def build(self):
return MyWidget()
if __name__ == '__main__':
MyApp().run()
答案 0 :(得分:2)
你走了:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
import os
Builder.load_string("""
<MyWidget>:
id: my_widget
input_text: input_text
Button
text: "open"
on_release: my_widget.open(filechooser.path, filechooser.selection)
TextInput:
id: input_text
text: '??????'
FileChooserListView:
id: filechooser
on_selection: my_widget.selected(filechooser.selection)
""")
class MyWidget(BoxLayout):
def open(self, path, filename):
with open(os.path.join(path, filename[0])) as f:
contents=f.read()
self.input_text.text=contents
def selected(self, filename):
print ("selected: %s" % filename[0])
class MyApp(App):
def build(self):
return MyWidget()
if __name__ == '__main__':
MyApp().run()
有三个错误。
在kivy代码中,您需要在顶层添加text_input的id:
import os
Builder.load_string("""
<MyWidget>:
id: my_widget
input_text: input_text # NOTE THIS LINE
TextInput:
id: input_text
text: '??????'
""")
您不应该使用MyWidget.input_text.text=contents
,因为MyWidget
是一个类名,而不是您正在处理的实例。使用self.input_text.text=contents
最后,在您致电print(f.read())
之后,除非您将其回复,否则您无法再阅读该文件,因此下一行contents=f.read()
将导致空contents
变量。
还需要引用TextInput.text
,但我想你知道这一点。