Python+kivy+SQLite: How to set label initial value and how to update label text?

2024/10/14 15:27:46

everyone,

I want to use kivy+Python to display items from a db file.

To this purpose I have asked a question before: Python+kivy+SQLite: How to use them together

The App in the link contains one screen. It works very well.

Today I have changed the App to two screens. The first screen has no special requirement but to lead the App to the second screen. In the second screen there is a label and a button. By clicking the button I want to have the label text changed. The label text refers to the car type from the db file that I have in the link above.

For this two screens design, I have two questions:

Question 1: How to update the label text when the button is clicked?

I tried with two methods:

Method A: self.ids.label.text = str(text)
It shows me the error message: AttributeError: 'super' object has no attribute '__getattr__' I have googled a lot but still cannot understand.

Method B: self.ids["label"].text = str(text) It shows me the error message: KeyError: 'label' I am confused because I have the label defined.

Question 2: How to set the label origin text to one of the car type, so that everytime the second screen is shown, there is already a car type shown.

Here is the code: (For the db file please refer to the link above.)

# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.base import runTouchApp
from kivy.lang import Builder
from kivy.properties import ListProperty
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.graphics import Rectangle
from kivy.properties import NumericProperty, StringProperty, BooleanProperty, ListProperty
from kivy.base import runTouchApp
from kivy.clock import mainthreadimport sqlite3
import randomclass MyScreenManager(ScreenManager):def init(self, **kwargs):super().__init__(**kwargs)@mainthread  # execute within next framedef delayed():self.load_random_car()delayed()def load_random_car(self):conn = sqlite3.connect("C:\\test.db")cur = conn.cursor()cur.execute("SELECT * FROM Cars ORDER BY RANDOM() LIMIT 1;")currentAll = cur.fetchone()conn.close()currentAll = list(currentAll)   # Change it from tuple to listprint currentAllcurrent    = currentAll[1]print currentself.ids.label.text = str(current)    # Method A
#        self.ids["label"].text = str(current) # Method B class FirstScreen(Screen):passclass SecondScreen(Screen):passroot_widget = Builder.load_string('''
#:import FadeTransition kivy.uix.screenmanager.FadeTransition
MyScreenManager:transition: FadeTransition()FirstScreen:SecondScreen:<FirstScreen>:name: 'first'BoxLayout:orientation: 'vertical'Label:text: "First Screen"font_size: 30Button:text: 'Go to 2nd Screen'font_size: 30on_release:  app.root.current = 'second'<SecondScreen>:name: 'second'BoxLayout:orientation: 'vertical'Label:id: labeltext: 'click to get a new car'   # I want its text changed when the button is clicked everytime. And its original text value should be one of the random car type from the db file.font_size: 30Button:text: 'Click to get a random car'font_size: 30on_release:  app.root.load_random_car()''')class ScreenManager(App):def build(self):return root_widgetif __name__ == '__main__':ScreenManager().run()

I have read a lot from internet, but I cannot understand them all. :-(

Please help me to correct the code. Thank you so much!

Answer
from kivy.app import App
from kivy.lang import Builder
from kivy.properties import StringProperty
from kivy.uix.widget import WidgetBuilder.load_string("""
<ScreenX>BoxLayout:orientation: 'vertical'Label:text: root.label_textButton:text: 'Click Me'on_release: root.on_clicked_button()
""")class ScreenX(Widget):label_text = StringProperty("Default Value")def on_clicked_button(self):self.label_text = "New Text!"class MyApp(App):def build(self):return ScreenX()MyApp().run()

is typically how you would do this ...

https://en.xdnf.cn/q/117945.html

Related Q&A

how to debug ModelMultipleChoiceField [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 7 years ago.Improve…

Standardization/preprocessing for 4-dimensional array

Id like to standardize my data to zero mean and std = 1. The shape of my data is 28783x4x24x7, and it can thought of as 28783 images with 4 channels and dimensions 24x7. The channels need to be standar…

My Python number guessing game

I have been trying to make a number guessing game for Python and so far it has altogether gone quite well. But what keeps bugging me is that it resets the number on every guess so that it is different,…

Class that takes another class as argument, copies behavior

Id like to create a class in Python that takes a single argument in the constructor, another Python class. The instance of the Copy class should have all the attributes and methods of the original clas…

Simple python script to get a libreoffice base field and play on vlc

Ive banged my head for hours on this one, and I dont understand the LibreOffice macro api well enough to know how to make this work:1) This script works in python:#!/usr/bin/env python3 import subproce…

Print month using the month and day

I need to print month using the month and day. But I cannot seem to move the numbers after 1 to the next line using Python.# This program shows example of "November" as month and "Sunday…

Maya: Defer a script until after VRay is registered?

Im trying to delay a part of my pipeline tool (which runs during the startup of Maya) to run after VRay has been registered. Im currently delaying the initialization of the tool in a userSetup.py like…

Optimization on Python list comprehension

[getattr(x, contact_field_map[communication_type])for x in curr_role_group.contacts ifgetattr(x, contact_field_map[communication_type])]The above is my list comprehension. The initial function and the …

tensorflow Word2Vec error

I downloaded source code of word2vec in github below. https://github.com/tensorflow/models/blob/master/tutorials/embedding/word2vec.py I am using tensorflow on pycharm. Im using windows 10. I installed…

Mysterious characters at the end of E-Mail, received with socket in python

I am not sure if this is the right forum to ask, but I give it a try. A device is sending an E-Mail to my code in which I am trying to receive the email via a socket in python, and to decode the E-Mail…