我在 kivy 应用程序中保存和读取文件时遇到问题。由于某种原因,保存文件后会出现新空格。
我认为重点是“文本末尾带有 ” 读取为一行,但输入为两行字段,然后保存为两行文件,这成为一个问题。
我签署了代码中处理文件的位置。 请帮助我,因为我自己也不明白。
测试.py '''
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
class Screeen(Screen):
None
class Manager(ScreenManager):
None
class appApp(App):
def on_start(self): # When the application starts, the file is read and the data is entered into the input fields
with open("settings.txt", 'r') as f:
self.a = f.readline()
self.b = f.readline()
self.c = f.readline()
f.close()
self.sm.get_screen("Screeen").ids.a.text = self.a
self.sm.get_screen("Screeen").ids.b.text = self.b
self.sm.get_screen("Screeen").ids.c.text = self.c
def on_stop(self): # after exiting the application, data from the input fields is saved to a file
with open("settings.txt", "w") as f:
f.write(self.sm.get_screen("Screeen").ids.a.text + "\n")
f.write(self.sm.get_screen("Screeen").ids.b.text + "\n")
f.write(self.sm.get_screen("Screeen").ids.c.text + "\n")
def __init__(self, **kwargs):
super().__init__(**kwargs)
# type-hint will help the IDE guide you to methods, etc.
self.sm: ScreenManager = Builder.load_file("test.kv")
def build(self):
return self.sm
if __name__ == "__main__":
appApp().run()
'''
测试.kv:
'''
Manager:
Screeen:
<Screeen>:
name: "Screeen"
FloatLayout:
size: root.width, root.height
TextInput:
id: a
text: ""
size_hint: (.25, .1)
pos: root.width * 1 / 3 , root.height * 3 / 4
TextInput:
id: b
text: ""
size_hint: (.25, .1)
pos: root.width * 1 / 3 , root.height * 2 / 4
TextInput:
id: c
text: ""
size_hint: (.25, .1)
pos: root.width * 1 / 3 , root.height * 1 / 4
'''
并且settings.txt为空
readline() 将返回终止换行符。因此,您可以将 on_start() 函数重写如下:
def on_start(self):
_ids = self.sm.get_screen("Screeen").ids
with open("settings.txt") as f:
for attr in "abc":
_ids[attr].text = f.readline().rstrip()