每个人,
我想用来kivy+Python
显示db
文件中的项目。
为此我之前问过一个问题:Python+kivy+SQLite: How to use them together
链接中的应用程序包含一个屏幕。它工作得很好。
今天我把App改成了两个屏幕。first screen
没有特殊要求,只需要将 App 引导到second screen
. 在second screen
里面有一个label
和一个button
。通过单击button
我想要label text
更改。label text
指的是我在上面链接中car type
的文件。db
对于这两个屏幕设计,我有两个问题:
问题1:label text
点击时如何更新button
?
我尝试了两种方法:
方法A: self.ids.label.text = str(text)
它向我显示错误消息:AttributeError: 'super' object has no attribute '__getattr__'
我google了很多但仍然无法理解。
方法 B: self.ids["label"].text = str(text)
它向我显示错误消息: KeyError: 'label'
我很困惑,因为我有label
定义。
问题2:如何设置label origin text
为一种车型,这样每次出现第二屏时,已经有车型出现了。
这是代码:(db file
请参阅上面的链接。)
# -*- 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 mainthread
import sqlite3
import random
class MyScreenManager(ScreenManager):
def init(self, **kwargs):
super().__init__(**kwargs)
@mainthread # execute within next frame
def 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 list
print currentAll
current = currentAll[1]
print current
self.ids.label.text = str(current) # Method A
# self.ids["label"].text = str(current) # Method B
class FirstScreen(Screen):
pass
class SecondScreen(Screen):
pass
root_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: 30
Button:
text: 'Go to 2nd Screen'
font_size: 30
on_release: app.root.current = 'second'
<SecondScreen>:
name: 'second'
BoxLayout:
orientation: 'vertical'
Label:
id: label
text: '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: 30
Button:
text: 'Click to get a random car'
font_size: 30
on_release: app.root.load_random_car()
''')
class ScreenManager(App):
def build(self):
return root_widget
if __name__ == '__main__':
ScreenManager().run()
我从互联网上阅读了很多内容,但我无法全部理解。:-(
请帮我更正代码。太感谢了!