SQLITE - To view the updates that have just been made to the application, it is necessary to sign out and sign in again

47 views
Skip to first unread message

Geraldo Zamparo

unread,
May 23, 2020, 3:40:04 PM5/23/20
to Kivy users support
1

I can normally update the records in the SQLITE database, the problem is when I view the updated record, it brings the old information, to bring the updated information it is necessary to exit the application and return.

What do I need to do to make the application automatically recognize changes made without having to leave?


CODE main.py:


from kivy.app import App

from kivy.uix.floatlayout import FloatLayout

from kivy.uix.screenmanager import ScreenManager, Screen

from kivy.uix.image import Image

from kivy.uix.widget import Widget

from kivy.core.audio import SoundLoader

from kivy.uix.filechooser import FileSystemLocal

from kivy.clock import Clock

from kivy.properties import NumericProperty, ListProperty

from kivy.animation import Animation

from random import random

import sqlite3

import json


class Manager(ScreenManager):

    pass


class Menu(Screen):

    try:

        conn = sqlite3.connect("datum.db") 

        cursor = conn.cursor()

        hscore = cursor.execute("""select highest_score from datum where id_score = 1""")

        hscore = cursor.fetchone()

        hscore = hscore[0]

        cursor.close()

    except:

        conn = sqlite3.connect('datum.db')

        cursor = conn.cursor()

        try:

            cursor.execute("""CREATE TABLE datum(id_score INTEGER NOT NULL, highest_score INTEGER, last_score INTEGER);""")

        except:

            pass

        cursor.execute("""INSERT INTO datum(id_score, highest_score, last_score) VALUES(1, 0, 0);""")

        conn.commit()

        hscore = cursor.execute("""select highest_score from datum where id_score = 1""")

        hscore = cursor.fetchone()

        hscore = hscore[0]

        cursor.close()


class Game(Screen):

    obstacles = []

    score = NumericProperty(0)


    def on_enter(self,*args):

        Clock.schedule_interval(self.update,1/30)

        Clock.schedule_interval(self.putObstacle,1)

        

    def on_pre_enter(self,*args):

        self.ids.player.y = self.height/2

        self.ids.player.speed = 0

        self.score = 0

        

    def update(self,*args):

        self.ids.player.speed += -self.height * 2 * 1/30

        self.ids.player.y += self.ids.player.speed * 1/30

        if self.ids.player.y > self.height or self.ids.player.y < 0:

            self.gameOver()

        elif self.playerCollided():

            self.gameOver()

    

    def putObstacle(self,*args):

        gap = self.height * 0.01

        position = (self.height-gap)*random()

        width = self.width * 0.001

        #obstaclelow   = Obstacle(x = self.width, height = position,                                   width = width)

        #obstaclehigh  = Obstacle(x = self.width, y = position+gap,  height = self.height-position-gap,width=width)

        obstacle1 = Obstacle(x = self.width, y = position+gap,  height = self.height-position-gap,width=width)

        obstacle2 = Obstacle(x = self.width, y = position+gap,  height = self.height-position-gap,width=width)

        #obstacle3 = Obstacle(x = self.width, y = position+gap,  height = self.height-position-gap,width=width)

        #obstacle4 = Obstacle(x = self.width, y = position+gap,  height = self.height-position-gap,width=width)

        #self.add_widget(obstaclelow,3)

        #self.add_widget(obstaclehigh,3)

        self.add_widget(obstacle1,3)

        self.add_widget(obstacle2,3)

        #self.add_widget(obstacle3,3)

        #self.add_widget(obstacle4,3)

        #self.obstacles.append(obstaclelow)

        #self.obstacles.append(obstaclehigh)

        self.obstacles.append(obstacle1)

        self.obstacles.append(obstacle2)

        #self.obstacles.append(obstacle3)

        #self.obstacles.append(obstacle4)

    

    def gameOver(self,*args):

        conn = sqlite3.connect("datum.db") 

        cursor = conn.cursor()

        highestscore =  cursor.execute("""select highest_score from datum where id_score = 1""")

        highestscore = cursor.fetchone()

        highestscore = highestscore[0]

        if self.score > highestscore:

            highestscore = self.score

        atualizar = cursor.execute("""UPDATE datum SET highest_score = ?, last_score = ?;""", (highestscore,self.score,))

        conn.commit()

        cursor.close()       

        

        Clock.unschedule(self.update,1/30)

        Clock.unschedule(self.putObstacle,1)

        for ob in self.obstacles:

            ob.anim.cancel(ob)

            self.remove_widget(ob)

        self.obstacles = []

        App.get_running_app().root.current = 'gameOver'

        

    def collided(self,wid1,wid2):

        if wid2.x <= wid1.x      + wid1.width  and \

           wid2.x +  wid2.width  >= wid1.x     and \

           wid2.y <= wid1.y      + wid1.height and \

           wid2.y +  wid2.height >= wid1.y:

            return True

        return False

    

    def playerCollided(self):

        collided = False

        for obstacle in self.obstacles:

            if self.collided(self.ids.player,obstacle):

                collided = True

                break

        return collided

        

    def on_touch_down(self,*args):

        self.ids.player.speed = self.height * 0.7


class Obstacle(Widget):

    #color = ListProperty([0.3,0.2,0.2,1])

    color = ListProperty([1,1,1,1])

    scored = False

    gameScreen = None

    

    def __init__(self,**kwargs):

        super().__init__(**kwargs)

        self.anim = Animation(x = -self.width,duration=3)

        self.anim.bind(on_complete = self.vanish)

        self.anim.start(self)

        self.gameScreen = App.get_running_app().root.get_screen('game')

        

    def on_x(self,*args):

        if self.gameScreen:

            if self.x < self.gameScreen.ids.player.x and not self.scored:

                self.gameScreen.score += 1

                self.scored = True

    

    def vanish(self,*args):

        self.gameScreen.remove_widget(self)

        self.gameScreen.obstacles.remove(self)

    

class GameOver(Screen):

    try:

        conn = sqlite3.connect("datum.db") 

        cursor = conn.cursor()

        lastscore = cursor.execute("""select last_score from datum where id_score = 1""")

        lastscore = cursor.fetchone()

        lastscore = lastscore[0]

        cursor.close()

    except:

        conn = sqlite3.connect('datum.db')

        cursor = conn.cursor()

        cursor.execute("""CREATE TABLE datum(id_score INTEGER NOT NULL, highest_score INTEGER, last_score INTEGER);""")

        cursor.execute("""INSERT INTO datum(id_score, highest_score, last_score) VALUES(1, 0, 0);""")

        cursor.commit()

        lastscore = cursor.execute("""select last_score from datum where id_score = 1""")

        lastscore = cursor.fetchone()

        lastscore = lastscore[0]

        cursor.close()


class Player(Image):

    speed = NumericProperty(0)

    

class Test(App):

    pass

   

Test().run()

Elliot Garbus

unread,
May 23, 2020, 5:06:54 PM5/23/20
to kivy-...@googlegroups.com

Where (what line) do you have the problem.  I’ll assume you have a problem with hscore.

 

The code at the top of Menu looks problematic.  I’d suggest most (or all)  of this code should be in a __init__ (),  you should use a kivy property, and use that property in your kv code to have it automatically update.  This code is only running when the Menu is created, is that what you want?  If you want it to run every time the screen is displayed, put it under on_enter()

--
You received this message because you are subscribed to the Google Groups "Kivy users support" group.
To unsubscribe from this group and stop receiving emails from it, send an email to kivy-users+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/kivy-users/fec3323e-01cf-464c-8dc8-4230adff67ef%40googlegroups.com.

 

Geraldo Zamparo

unread,
May 23, 2020, 7:27:47 PM5/23/20
to Kivy users support
@Elliot, do you have an example for this part that you commented
"should you use a kivy property and use it in your kv code to have it update automatically" ?

To unsubscribe from this group and stop receiving emails from it, send an email to kivy-...@googlegroups.com.

Elliot Garbus

unread,
May 23, 2020, 8:52:09 PM5/23/20
to kivy-...@googlegroups.com

Here is an example of a digital clock that uses a kivy StringProperty to display the time.

In the class MyClock, the StringProperty current_time is created.  Update time, writes the time string to current_time, once each second.

Because this is a kivy property, the changes are automatically bound to the text field, and it updates automatically.

 

 

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.clock import Clock
from kivy.properties import StringProperty

from time import strftime
kv =
"""
BoxLayout:
    orientation: 'vertical'
    MyClock:
        font_size: 50
        text: self.current_time    # This is the StringProperty of MyClock
    Label:
        size_hint_y: .2
        text: 'Simple Clock'
        font_size: 50

"""


class MyClock(Label):
    current_time = StringProperty(strftime(
"%I:%M:%S %p"))

   
def __init__(self, **kwargs):
        Clock.schedule_interval(
self.update_time, 1)
       
super().__init__(**kwargs)

   
def update_time(self, dt):
       
self.current_time = strftime("%I:%M:%S %p")


class SimpleClockApp(App):
   
def build(self):
       
return Builder.load_string(kv)


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

To unsubscribe from this group and stop receiving emails from it, send an email to kivy-users+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/kivy-users/f43e091d-15c3-4aa1-a5af-c7037a189f1b%40googlegroups.com.

 

Geraldo Zamparo

unread,
May 23, 2020, 9:34:48 PM5/23/20
to Kivy users support
@Elliot, in the .kv file, according to your example, changing the code "text: 'Highest Score:' + str (root.hscore)" to "text: 'Highest Score:' + str (self.hscore)" and it didn't work. Any suggestion ?

I use the code in the .kv file:

<Menu>:
BoxLayout:
canvas:
Color:
rgba: 1,1,1,1
Rectangle:
size:self.size
pos: self.pos
source: '000_background.png'
orientation: 'vertical'
padding: '200dp','50dp'
spacing:'100dp'
Label:
text: 'Highest Score: ' + str(root.hscore)
color: 125,0,27,1
font_size: '20sp'
bold: True
size_hint_y: None
height: self.font_size
y: root.height*0.99-self.height
Widget:
BoxLayout:
padding: '55dp'
spacing: '450dp'
MenuButton:
text: 'Start Game'
font_name: 'Arial'
on_release: app.root.current = 'game'
MenuButton:
text: 'Exit Game'
on_release: app.stop()

Elliot Garbus

unread,
May 23, 2020, 9:58:50 PM5/23/20
to kivy-...@googlegroups.com
Show where hscore is declared. 

Sent from my iPhone

On May 23, 2020, at 6:34 PM, Geraldo Zamparo <geraldo...@gmail.com> wrote:


To unsubscribe from this group and stop receiving emails from it, send an email to kivy-users+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/kivy-users/f565e758-a1e2-4801-a32c-73ffbadd1d52%40googlegroups.com.

Geekademy

unread,
May 23, 2020, 10:07:34 PM5/23/20
to kivy-...@googlegroups.com

On 2020-05-23 12:40, Geraldo Zamparo wrote:
> I can normally update the records in the SQLITE database, the problem is when I
> view the updated record, it brings the old information, to bring the updated
> information it is necessary to exit the application and return.
>
> What do I need to do to make the application automatically recognize changes
> made without having to leave?


I'd write a python script with only sqlite until I understood how it works. My
guess, without writing the script myself, is that you have transactions enabled
and are not executing the "COMMIT;" statement.

Cheers,

Geraldo Zamparo

unread,
May 23, 2020, 11:01:32 PM5/23/20
to Kivy users support
I declare the "hscore" with the code:

        hscore = cursor.execute("""select highest_score from scores where id_score = 1""")
        hscore = cursor.fetchone()
        hscore = hscore[0]

Elliot Garbus

unread,
May 23, 2020, 11:07:04 PM5/23/20
to kivy-...@googlegroups.com

from kivy.properties import NumericProperty

class Menu(Screen):

    hscore = NumericProperty()    # you can put an initial value here, like NumericPropety(0)

   

    def __init__(self, **kwargs):

        self.hscore = cursor.execute("""select highest_score from scores where id_score = 1""")

        self.hscore = cursor.fetchone()[0]

        super().__init__(**kwargs)

--

You received this message because you are subscribed to the Google Groups "Kivy users support" group.
To unsubscribe from this group and stop receiving emails from it, send an email to kivy-users+...@googlegroups.com.

Geraldo Zamparo

unread,
May 23, 2020, 11:20:28 PM5/23/20
to Kivy users support
@Geekademy, in each inclusion or update command I use on the line below, I place the command "conn.commit()", for example:
cursor.execute ("" "INSERT INTO scores (id_score, highest_score, last_score) VALUES (1, 0, 0);" "")
conn.commit()
or:
update = cursor.execute ("" "UPDATE scores SET highest_score =?, last_score =?;" "", (highestscore, self.score,))
conn.commit()
As you can see in my previously published code. Taking into account that the commit field is present, what suggests that it could be the problem?
Remembering that with the app running and after updating the information, I go to sqlite and there it is updated, only the app does not update.

Em sábado, 23 de maio de 2020 21:52:09 UTC-3, Elliot Garbus escreveu:

Geraldo Zamparo

unread,
May 23, 2020, 11:43:31 PM5/23/20
to Kivy users support
@Elliot, I inserted the code as proposed:

class Menu(Screen):
    hscore = NumericProperty()
    def __init__(self,**kwargs):
        conn = sqlite3.connect("datum.db")
        cursor = conn.cursor()
        self.hscore = cursor.execute("""select highest_score from scores where id_score = 1""")
        self.hscore = cursor.fetchone()[0]
        cursor.close()
        super().__init__(**kwargs)

When running python returned the error:

Traceback (most recent call last):
   File "main.py", line 191, in <module>
     HandicapInBaseball().run()
   File "C:\Users\Admin\AppData\Local\Programs\Python\Python37\lib\site-packages\kivy\app.py", line 828, in run
     self.load_kv(filename=self.kv_file)
   File "C:\Users\Admin\AppData\Local\Programs\Python\Python37\lib\site-packages\kivy\app.py", line 599, in load_kv
     root = Builder.load_file(rfilename)
   File "C:\Users\Admin\AppData\Local\Programs\Python\Python37\lib\site-packages\kivy\lang\builder.py", line 301, in load_file
     return self.load_string(data, **kwargs)
   File "C:\Users\Admin\AppData\Local\Programs\Python\Python37\lib\site-packages\kivy\lang\builder.py", line 405, in load_string
     rule_children=rule_children)
   File "C:\Users\Admin\AppData\Local\Programs\Python\Python37\lib\site-packages\kivy\lang\builder.py", line 654, in _apply_rule
     child = cls(__no_builder=True)
   File "main.py", line 23, in __init__
     self.hscore = cursor.execute("""select highest_score from scores where id_score = 1""")
   File "kivy\properties.pyx", line 497, in kivy.properties.Property.__set__
   File "kivy\properties.pyx", line 526, in kivy.properties.Property.set
   File "kivy\properties.pyx", line 657, in kivy.properties.NumericProperty.convert
 ValueError: Menu.hscore has an invalid format (got <sqlite3.Cursor object at 0x000002744D283030>)

How do you suggest I can solve it?

To unsubscribe from this group and stop receiving emails from it, send an email to kivy-...@googlegroups.com.

Elliot Garbus

unread,
May 23, 2020, 11:56:37 PM5/23/20
to kivy-...@googlegroups.com
What data type is the dB returning?
I assumed hscore is a number.  Can you convert the cursor object to a number?
Print out the data coming from the dB, is it what you expect? 

Sent from my iPhone

On May 23, 2020, at 8:43 PM, Geraldo Zamparo <geraldo...@gmail.com> wrote:


To unsubscribe from this group and stop receiving emails from it, send an email to kivy-users+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/kivy-users/c346d8d1-da3d-4d94-b457-924ff49a2262%40googlegroups.com.

Geraldo Zamparo

unread,
May 24, 2020, 12:10:17 AM5/24/20
to Kivy users support
@Elliot, Yes, the information I need is a number.
The sqlite initially displays the information: "sqlite3.Cursor object at 0x000002744D283030" and only after the command "cursor.fetchone () [0]" does the information become a number.
So this is in conflict with "NumericProperty ()".

Elliot Garbus

unread,
May 24, 2020, 12:16:22 AM5/24/20
to kivy-...@googlegroups.com

So only assign to self.hscore when you have the final vaule, use something else for the intermediate values.

To unsubscribe from this group and stop receiving emails from it, send an email to kivy-users+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/kivy-users/710770cc-6967-4d03-8a1e-42cc248a2d02%40googlegroups.com.

 

Geraldo Zamparo

unread,
May 24, 2020, 12:36:17 AM5/24/20
to Kivy users support
@Elliot, thank you for the informations. Returning to the initial question that the commands for creating and updating data in sqlite3 are working, the problem is in getting this information on the application screen after being updated.
When information is updated within the application, I go to the sqlite3 database and it is saved, but if I call this information by the "select" command, the old information is shown. To show the updated information, it is necessary to exit the application and enter the application again.
What is your suggestion to solve this?

Elliot Garbus

unread,
May 24, 2020, 12:43:03 AM5/24/20
to kivy-...@googlegroups.com

Sounds like your problem is with SQLite.  I’m not familiar with SQL. 

To unsubscribe from this group and stop receiving emails from it, send an email to kivy-users+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/kivy-users/9f5d897a-b214-4862-bf55-966c8aeb9529%40googlegroups.com.

 

Reply all
Reply to author
Forward
0 new messages