I have this code:
import pymysql
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.button import Button
db = pymysql.connect("host", "user", "password", "database")
cursor = db.cursor()
cursor.execute("SELECT phone_info FROM ants WHERE id='onexT1'")
data_list = cursor.fetchall()
hello = list(data_list)
class ViewButton(Button):
def print_data(self, data):
print(data)
KV = '''
<ViewButton>:
on_release:
root.print_data(self.data)
RecycleView:
data: ()
viewclass: 'ViewButton'
RecycleBoxLayout:
default_size_hint: 1, None
orientation: 'vertical'
'''
class Test(App):
def build(self):
root = Builder.load_string(KV)
root.data = (item for item in hello)
return root
if __name__ == '__main__':
Test().run()
Basically, the result from the query in the database is stored as a tuple. However when I run it, it returns an error:
AttributeError: 'tuple' object has no attribute 'get'
So I tried converting the tuple to a list but it returns the same error as above.
What I want is to display the contents of the tuple/list in a table using recycleview. Thanks :)
RecycleView needs an iterable of a hashtable, for example a list of dictionaries, where the keys of the dictionaries are the properties that will be used in the viewclass, this is indicated in the docs:
data:
The data used by the current view adapter. This is a list of dicts whose keys map to the corresponding property names of the viewclass.
data is an AliasProperty that gets and sets the data used to generate the views.
fetchall returns a list of tuples, and we must convert that list of tuples to a list of dictionaries, where the dictionary key is "text" since it is the property that is used by ViewButton.
On the other hand ViewButton does not have the data property but text, so you must save that information.
...
data_list = cursor.fetchall()
hello = [({"text": result[0]}) for result in data_list] # convert
class ViewButton(Button):
def print_data(self, data):
print(data)
KV = '''
<ViewButton>:
on_release:
root.print_data(self.text) # <---
RecycleView:
viewclass: 'ViewButton'
RecycleBoxLayout:
default_size_hint: 1, None
orientation: 'vertical'
'''
class Test(App):
def build(self):
root = Builder.load_string(KV)
root.data = hello
return root
if __name__ == '__main__':
Test().run()