【问题标题】:Updating a label from another class从另一个类更新标签
【发布时间】:2021-03-26 03:27:16
【问题描述】:

当我按下AddTask类中的按钮save时,文本输入中的文本将直接更新为@987654323中的Label @类。

kivy.py

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from KivyCalendar import DatePicker
from kivy.lang import Builder
from kivy.uix.popup import Popup
from kivy.properties import ObjectProperty
from database import DataBase
from database2 import DataBase2
from kivy.uix.label import Label
from kivy.core.window import Window
Window.size = (300,600)
from kivy.config import Config
Config.set('graphics', 'resizable', '0')
Config.set('graphics', 'width', '300')


Builder.load_file('window.kv')


class HalamanUtama(Screen):
    def submit (self):
        name = self.ids.TaskName.text
        self.ids.task_one.text = name

    def next(self):
        layout = self.ids['invoices']
        arr = db.get_data()
        for invoice in arr:
            lab1 = Label(text=invoice, size_hint_x=.35, halign='left')
            layout.add_widget(lab1)


class AddTask(Screen):
    names = ObjectProperty(None)
    desc = ObjectProperty(None)
    deadline = ObjectProperty(None)
    reminder1 = ObjectProperty(None)

    def submit(self):
        if self.names.text != "" and self.desc.text != "" and self.deadline.text != "" and self.reminder1.text != "":

            db.add_task(self.names.text, self.desc.text, self.deadline.text, self.reminder1.text)
            self.reset()
            hu = HalamanUtama()
            return hu.next()

        else:
            invalidForm()

    def reset(self):
        self.names.text = ""
        self.desc.text = ""
        self.deadline.text = ""
        self.reminder1.text = ""

    def update_value(self, inst):
        """ Update textinput value on popup close """
        self.text = "%s-%s-%s" % tuple(self.cal.active_date)
        self.focus = False
        App.get_running_app().root.ids.deadline.text = self.text

    def show_calendar(self):
        datePicker.show_popup(1, .3)


class DetailTask(Screen):
    def btn(self):
        shows = Delete()

        popupWindow = Popup(title="Delete Task", content=shows, separator_height=0, size_hint=(None, None),
                            size=(230, 230))
        popupWindow.open()


class UncompletedExam(Screen):
    def next(self):
        layout = self.ids['idk']
        arr = db2.get_data()
        for Idk in arr:
            lab2 = Label(text=Idk, size_hint_x=.35, halign='left')
            layout.add_widget(lab2)

class AddExam(Screen):
    namess = ObjectProperty(None)
    descc = ObjectProperty(None)
    deadlinee = ObjectProperty(None)
    reminder11 = ObjectProperty(None)


    def submit(self):
        if self.namess.text != "" and self.descc.text != "" and self.deadlinee.text != "" and self.reminder11.text != "":

            db2.add_exam(self.namess.text, self.descc.text, self.deadlinee.text, self.reminder11.text)
            self.reset()
            ue = UncompletedExam()
            return ue.next()

        else:
            invalidForm()

    def update_value(self, inst):
        """ Update textinput value on popup close """
        self.text = "%s-%s-%s" % tuple(self.cal.active_date)
        self.focus = False
        App.get_running_app().root.ids.deadlinee.text = self.text

    def show_calendar(self):
        datePicker.show_popup(1, .3)

    def reset(self):
        self.namess.text = ""
        self.descc.text = ""
        self.deadlinee.text = ""
        self.reminder11.text = ""

class DetailExam(Screen):
    pass

class WindowsManager(ScreenManager):
    pass


class Delete(Screen):
    pass


class ListYPP(App):
    def build(self):
        return WindowsManager()

    def vibrate(self, time):
        vibrator.vibrate(time=5)

    def pattern(self, pattern):
        vibrator.pattern([0, 0, 1, 2])

    def exists(self):
        return self._exists()

    def cancel(self):
        self._cancel()

        # private

    def _vibrate(self, **kwargs):
        raise NotImplementedError()

    def _pattern(self, **kwargs):
        raise NotImplementedError()

    def _exists(self, **kwargs):
        raise NotImplementedError()

    def _cancel(self, **kwargs):
        raise NotImplementedError()

def invalidLogin():
    pop = Popup(title='Invalid Login',
                content=Label(text='Invalid username or password.'),
                size_hint=(None, None), size=(300, 300))
    pop.open()


def invalidForm():
    pop = Popup(title='Invalid Form',
                content=Label(text='Please fill in all inputs with valid information.', font_size= 14.7),
                size_hint=(None, None), size=(300, 300))

    pop.open()

db2 = DataBase2("examdetail.txt")
db = DataBase("taskdetail.txt")

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

数据库.py

import datetime
from KivyCalendar import DatePicker
from kivy.config import Config

Config.set('graphics', 'resizable', '0')
Config.set('graphics', 'width', '300')

class DataBase:
    def __init__(self, filename):
        self.filename = filename
        self.taskdetails = None
        self.file = None
        self.load()

    def load(self):
        self.file = open(self.filename, "r")
        self.taskdetails = {}

        for line in self.file:
            taskname, desc, deadline, reminder1 = line.strip().split(";")
            self.taskdetails[taskname] = (desc, deadline, reminder1)
        self.file.close()

    def add_task(self, taskname, desc, deadline, reminder1):
        if taskname.strip() not in self.taskdetails:
            self.taskdetails[taskname.strip()] = (desc.strip(), deadline.strip(), reminder1.strip())
            self.save()
            return 1
        else:
            print("Task Name exists already")
            return -1

    def get_data(self):
        FullDetails = self.taskdetails
        return FullDetails

    def save(self):
        with open(self.filename, "w") as f:
            for detail in self.taskdetails:
                f.write(detail + ";" + self.taskdetails[detail][0] + ";" + self.taskdetails[detail][1] + ";" + self.taskdetails[detail][2] + "\n")

    @staticmethod
    def get_date():
        return str(datetime.datetime.now()).split(" ")[0]

database2.py

import datetime

class DataBase2:
    def __init__(self, filename):
        self.filename = filename
        self.examdetails = None
        self.file = None
        self.load()

    def load(self):
        self.file = open(self.filename, "r")
        self.examdetails = {}

        for line in self.file:
            examname, descc, deadlinee, reminder11 = line.strip().split(";")
            self.examdetails[examname] = (descc, deadlinee, reminder11)
        self.file.close()

    def add_exam(self, examname, descc, deadlinee, reminder11):
        if examname.strip() not in self.examdetails:
            self.examdetails[examname.strip()] = (descc.strip(), deadlinee.strip(), reminder11.strip())
            self.save()
            return 1
        else:
            print("Exam Name exists already")
            return -1

    def get_data(self):
        FullDetails = self.examdetails
        return FullDetails

    def save(self):
        with open(self.filename, "w") as f:
            for detail in self.examdetails:
                f.write(detail + ";" + self.examdetails[detail][0] + ";" + self.examdetails[detail][1] + ";" + self.examdetails[detail][2] + "\n")

    @staticmethod
    def get_date():
        return str(datetime.datetime.now()).split(" ")[0]

windows.kv

#:import FadeTransition kivy.uix.screenmanager.FadeTransition

<WindowsManager>:
    transition: FadeTransition()
    HalamanUtama:
    AddTask:
    DetailTask:
    UncompletedExam:
    AddExam:
    DetailExam:
    Delete:

<HalamanUtama>:
    name : "halamanutama"
    invoices:invoices

    FloatLayout:
        Image:
            source: 'REVISI TASK.jpg'
            pos_hint:{'left':1, 'top':1}
            size_hint : 1,1
            allow_stretch : True
            keep_ratio : False

    GridLayout:
        id: invoices
        cols: 1
        #orientation: "horizontal"
        padding : 5, 5
        spacing: 10, 10
        #size: 100, 50
        size_hint: 1, 0.7
        pos_hint: {'center_x':0.5, 'center_y':0.440}


        Button:
            text: ""
            background_color: 0,0,0,0
            canvas.before:
                Color:
                    rgba: 0,0,0,1
                Line:
                    width: 1
                    rectangle: self.x, self.y, self.width, self.height
            color: 0,0,0,1
            text_size: self.size
            halign: 'center'
            valign: 'middle'

        Button:
            text: ""
            background_color: 0,0,0,0
            canvas.before:
                Color:
                    rgba: 0,0,0,1
                Line:
                    width: 1
                    rectangle: self.x, self.y, self.width, self.height
            color: 0,0,0,1
            text_size: self.size
            halign: 'center'
            valign: 'middle'

        Button:
            text: ""
            background_color: 0,0,0,0
            canvas.before:
                Color:
                    rgba: 0,0,0,1
                Line:
                    width: 1
                    rectangle: self.x, self.y, self.width, self.height
            color: 0,0,0,1
            text_size: self.size
            halign: 'center'
            valign: 'middle'

        Button:
            text: ""
            background_color: 0,0,0,0
            canvas.before:
                Color:
                    rgba: 0,0,0,1
                Line:
                    width: 1
                    rectangle: self.x, self.y, self.width, self.height
            color: 0,0,0,1
            text_size: self.size
            halign: 'center'

但它不起作用。谁能帮我解决这个问题?

【问题讨论】:

  • 您的 kv 文件格式错误。无法重现。它以kivy.lang.parser.ParserException 失败,因为Identifier missing 在您的windows.kv 中冒号附近的第3 行。请修复 kv 文件并发布minimal reproducible example。也许您可以删除所有不相关的依赖项,例如DataBaseDataBase2DatePicker

标签: python android testing kivy


【解决方案1】:

你可以用 PutExtra 来做这件事

【讨论】:

    【解决方案2】:

    注意: 如果你能理解这个例子,它将证明是有用的,并且很容易解决你的问题。

    你的 main.py
    class textinput_screen(widget):
        def __init__(self, **kwargs):
            supper().__init__(**kwargs)
    
        def pull_text(self):
           self.text_input = self.ids.ID_text_input.text 
           
    
    class labelupdate_screen(widget):
        text_input_update = StringProperty()
        def __init__(self, **kwargs):
            supper().__init__(**kwargs)
            self.text_input_update = textinput_screen.text_input
    
    class theapp(App):
        def build(self):
            self.screenm = ScreenManager()
    
            self.screen = Screen(name = "text input screem")
            screen.add_widget(self.textinput_screen)
    
            self.screen = Screen(name = "label update screen")
            screen.add_widget(self.labelupdate_screen)
    
    
            self.screenm.add_widget(screen)
    if __name__ = "__main__":
        theapp.run()
    
    你的 kivy 文件
    <textinput_screen>
        ####your widgets####
        TextInput:
            id: Id_text_input
            text_hint: 'text input .... or something'
    
    <labelupdate_screen>
         ####ur widgets#####
         Label:
             Text: root.text_input_update
    

    注意: 关于这个问题有很多类似的问题。这个问题的主要原因是很多人过于依赖kivy-lang,text_input(.text)label(.text)被认为是widget属性,如果你打算修改它然后在另一个widget或屏幕中重新使用它那么你必须将它作为一个类内或类之间的变量传递。在这种情况下,类中的 textinput.text 由 id 检索,然后作为 stringproperty 传递给另一个类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-18
      • 1970-01-01
      • 2013-05-06
      • 2013-01-31
      • 2017-08-10
      • 2018-01-16
      • 1970-01-01
      • 2014-02-14
      相关资源
      最近更新 更多