【问题标题】:Python Kivy. My program should append the textfile, but is does not蟒蛇基维。我的程序应该附加文本文件,但不是
【发布时间】:2018-08-12 03:15:56
【问题描述】:

文本文件应如下所示:

例如

Walking 61.0/2018-09-04 79.0/2018-10-04   
Running 24.0/2018-09-04 33.0/2018-10-04   

这个函数的重点是在文本文件中追加滑块的新值或改变一个。

滑块有一些名称,每个名称都可以有多个值,其中包括一个滑块值和当前日期。如果今天不是最后一个值的日期 - 那么我们附加文件。

如果今天与最后一个值的日期相同 - 那么它应该改变它(我还没有这样做,但这不是问题,我会在解决这个问题后自己做) .

这里是完整的 Python 文件和 Kivy 文件,只有 def save_values 很重要。其他一切只是为了让程序为您工作。

Python

from kivy.app import App

import time
import datetime


from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.lang import Builder
from kivy.uix.slider import Slider
from kivy.uix.widget import Widget
from kivy.uix.textinput import TextInput

from kivy.uix.boxlayout import BoxLayout
from kivy.uix.anchorlayout import AnchorLayout

from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition

from kivy.config import Config

screen_width = 450
screen_height = 800

Config.set("graphics", "resizable","1")
Config.set("graphics", "width", screen_width)

Config.set("graphics", "height", screen_height)

languages = ["Reading","Writing","Running","Climbing"]
spawned_List = ["False"]


class MenuScreen(Screen):
    pass

class JobChoiceScreen(Screen):
    def changing_screen(self, instance, *args):
        self.manager.current= "sliderScreen"

        screenSlider = self.manager.get_screen('sliderScreen')
        text = str(instance.text)

        screenSlider.changing_label(text)

    def on_pre_enter(self, *args):
        if spawned_List[0] == "False":
            for x in range(0,len(languages)):
                word = languages[x]
                word = str(word)
                btn = Button(text = word, size_hint=(None, None), size = (140,70),
                font_size = 18, bold = True, color = [0,1,1,1], background_color = (.156, .172, .24, 0.7),
                on_release = self.changing_screen)

                self.ids.container.add_widget(btn)

                spawned_List[0] = "True"

            self.ids.boxLayBottom.add_widget(Widget(size_hint=(1, .4)))

            self.ids.datesContainer.add_widget(Button(text = "Day back", size_hint=(.28, 1), font_size = 18, bold = True, color = [0,1,1,1], background_color = (.176, .192, .44, 0.7)))
            self.ids.datesContainer.add_widget(Widget(size_hint=(.44, 1)))
            self.ids.datesContainer.add_widget(Button(text = "Day forward", size_hint=(.28, 1), font_size = 18, bold = True, color = [0,1,1,1], background_color = (.176, .192, .44, 0.7)))

class SliderScreen(Screen):


    def save_values(self, *args, **kwargs):
        date = (datetime.datetime.now().strftime("%y-%m-%d"))
        written = (str(self.ids.my_slider.value)+ "/" + date + " ")
        print("started save_values")

        with open('values.txt', 'r') as fileValues:
            lines = fileValues.readlines()
            print("opened the file")

            with open('values.txt', 'a') as fileValues:
                for i, line in enumerate(lines):
                    if line.startswith(self.ids.my_label.text) and line.find(date) == -1:
                        line = line + ((self.ids.my_label.text) + " " + written)
                        print(line)

                        if not line.startswith(self.ids.my_label.text) and line.find(date) == -1:
                            line = (" " + written)
                            print(line)
                            print("hello bill")

    def changing_label(self, text):
        self.ids.my_label.text = text


class ScreenManagement(ScreenManager):
    pass

presentation = Builder.load_file("manager.kv")

class MainApp(App):
    def build(self):
        return presentation

if __name__ == "__main__":
    MainApp().run()

基维

ScreenManagement:
    #transition: FadeTransition()
    MenuScreen:
    JobChoiceScreen:
    SliderScreen:

<MenuScreen>:
    canvas:
        Rectangle:
            source:"background.jpg"
            pos: self.pos
            size: self.size
    name: "menu"

    BoxLayout:
        padding: [10,10,10,10]
        orientation: "vertical"
        Widget:
            size_hint: [1,0.2]

        BoxLayout:

            Button:
                bold: True
                color: [0,1,1,1]
                on_release: app.root.current = "list_of_jobs"
                text: "Change"
                size_hint: [0.28,1]
                font_size: 20
                background_color: (.156, .172, .24, 0.7)

            Widget:
                size_hint: [0.44,1]

            Button:
                bold: True
                color: [.5,0, .8, .7]
                text: "View \n Progress"
                size_hint: [0.28,1]         
                font_size: 20
                halign: "center" 
                valign: "center"
                background_color: (.156, .172, .24, 0.7)
                on_release: app.root.current = "sliderScreen"

        Widget:
            size_hint: [1,0.2]


<JobChoiceScreen>:
    canvas:
        Rectangle:
            source:"background.jpg"
            pos: self.pos
            size: self.size

    name: "list_of_jobs"

    BoxLayout:
        orientation: "vertical"
        padding: [10,10,10,10]
        BoxLayout:
            orientation: "vertical"
            id: boxLayBottom
            size_hint: (1,.1)

            BoxLayout:
                id: datesContainer
                orientation: "horizontal"
                size_hint: (1,.6)
        AnchorLayout:
            anchor_x: "center"
            acnhor_y: "top"
            size_hint: (1,.8)

            GridLayout:
                id: container
                cols: 3
                spacing: 5

        BoxLayout:
            orientation: "vertical"
            id: boxContainer
            size_hint: (1,.1)

            Button:
                text: "Back to Menu" 
                on_release: app.root.current = "menu"
                bold: True
                color: [0,1,1,1]
                background_color: (.176, .192, .44, 0.7)

<SliderScreen>:
    canvas:
        Rectangle:
            source:"background.jpg"
            pos: self.pos
            size: self.size

    name: "sliderScreen"

    BoxLayout:
        padding: [10,10,10,10]
        orientation: "vertical"
        id: my_label_container

        Slider: 
            id: my_slider
            min: 0
            max: 100
            value: 0
            orientation: "vertical"
            size_hint: [1, 0.7]
            step: 1

        Label: 
            id: my_label
            size_hint: [1, 0.2]
            bold: True
            font_size: 40
            text: ""

        Button:
            size_hint: [1, 0.1]
            bold: True
            on_release: app.root.current = "menu"
            text : "Back Home"
            font_size: 20
            halign: "center" 
            valign: "center"
            background_color: (.156, .172, .24, 0.7)
            on_press: root.save_values()

定义保存值

def save_values(self, *args, **kwargs):
    date = (datetime.datetime.now().strftime("%y-%m-%d"))
    written = (str(self.ids.my_slider.value)+ "/" + date + " ")
    print("started save_values")

    with open('values.txt', 'r') as fileValues:
        lines = fileValues.readlines()
        print("opened the file")

        with open('values.txt', 'a') as fileValues:
            for i, line in enumerate(lines):
                if line.startswith(self.ids.my_label.text) and line.find(date) == -1:
                    line = line + ((self.ids.my_label.text) + " " + written)
                    print(line)

                    if not line.startswith(self.ids.my_label.text) and line.find(date) == -1:
                        line = (" " + written)
                        print(line)
                        print("hello bill")

【问题讨论】:

    标签: python kivy


    【解决方案1】:

    我发现您的代码有两个问题:

    1. 在您的save_values() 方法中,您以相同的名称同时打开两次values.txt 文件,但使用不同的模式。我认为您需要取消缩进第二个with open 块,删除第二个with open 语句,并将第一个with open 语句中的模式修改为r+。所以你的代码应该是这样的:

      with open('values.txt', 'r+') as fileValues:
          lines = fileValues.readlines()
          print("opened the file")
      
          for i, line in enumerate(lines):
      
    2. 您永远不会调用任何write 例程,因此不会写入任何内容。当您想在values.txt 上追加一行/行时,您需要调用fileValues.write()fileValues.writelines()

    我没有看过你的代码逻辑,所以我不会对此发表评论。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-17
      相关资源
      最近更新 更多