How to change the anchor value in MDFloatingActionButtonSpeedDial in KivyMD? - python

I have been working with kivymd to develop a mobile application. But I was having a problem regarding MDFloatingActionButtonSpeedDial. I wanted to set the anchor value in MDFloatingActionButtonSpeedDial to "left" for some buttons and "right" for some buttons. So I modified the class of MDFloatingActionButtonSpeedDial that is in the module "kivymd.uix.button" and added some more options in 'anchor' which assumes OptionProperty. Along with it I also added the methods required for the applied changes. The changes in acnhor are:-
anchor = OptionProperty('right',option=["right","left"])
And the changes in the methods are:-
def set_pos_labels(self, widget):
"""Sets the position of the floating labels."""
if self.anchor == "right":
widget.x = Window.width - widget.width - dp(86)
elif self.anchor == "left":
widget.x = widget.width + dp(86)
def set_pos_root_button(self, instance):
"""Sets the position of the root button."""
if self.anchor == "right":
instance.y = dp(20)
instance.x = Window.width - (dp(56) + dp(20))
elif self.anchor == "left":
instance.y = dp(20)
instance.x = (dp(56) + dp(20))
def set_pos_bottom_buttons(self, instance):
"""Sets the position of the bottom buttons in a stack."""
if self.anchor == "right":
if self.state != "open":
instance.y = instance.height / 2
instance.x = Window.width - (instance.height + instance.width / 2)
elif self.anchor == "left":
if self.state != "open":
instance.y = instance.height / 2
instance.x = (instance.height + instance.width / 2)
I have added the left anchor property as the right anchor was present by default.
The Builder string that I have written is as follows:-
MDFloatingActionButtonSpeedDial:
data : app.data_download
rotation_root_button : True
id : download_button
icon: 'download'
anchor: 'left'
MDFloatingActionButtonSpeedDial:
data : app.data_return
rotation_root_button: True
icon : 'arrow-left'
anchor: 'right'
Now whenever I tried to set the anchor property to 'left' other than the default option(right) in my builder string file the program returns an error. I want to inform if I set the default value of anchor to left then I get the error for setting the anchor to right and when I set the default value of anchor to right then I get the error for setting the anchor to left. The error that that I am getting is:-
Traceback (most recent call last):
File "C:\Users\user\Anaconda3\lib\site-packages\kivy\lang\builder.py", line 700, in _apply_rule
setattr(widget_set, key, value)
File "kivy\weakproxy.pyx", line 35, in kivy.weakproxy.WeakProxy.__setattr__
File "kivy\properties.pyx", line 497, in kivy.properties.Property.__set__
File "kivy\properties.pyx", line 541, in kivy.properties.Property.set
File "kivy\properties.pyx", line 532, in kivy.properties.Property.set
File "kivy\properties.pyx", line 1252, in kivy.properties.OptionProperty.check
ValueError: MDFloatingActionButtonSpeedDial.anchor is set to an invalid option 'left'. Must be one
of: []
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "onlinecv2.py", line 500, in <module>
ScanIt().run()
File "C:\Users\user\Anaconda3\lib\site-packages\kivy\app.py", line 829, in run
root = self.build()
File "onlinecv2.py", line 435, in build
camerascreen = Builder.load_string(screen_helper)
File "C:\Users\user\Anaconda3\lib\site-packages\kivy\lang\builder.py", line 405, in load_string
rule_children=rule_children)
File "C:\Users\user\Anaconda3\lib\site-packages\kivy\lang\builder.py", line 707, in _apply_rule
e), cause=tb)
kivy.lang.builder.BuilderException: Parser: File "<inline>", line 154:
...
152: id : download_button
153: icon: 'download'
>> 154: anchor: 'left'
155:
156:
...
ValueError: MDFloatingActionButtonSpeedDial.anchor is set to an invalid option 'left'. Must be one
of: []
File "C:\Users\user\Anaconda3\lib\site-packages\kivy\lang\builder.py", line 700, in _apply_rule
setattr(widget_set, key, value)
File "kivy\weakproxy.pyx", line 35, in kivy.weakproxy.WeakProxy.__setattr__
File "kivy\properties.pyx", line 497, in kivy.properties.Property.__set__
File "kivy\properties.pyx", line 541, in kivy.properties.Property.set
File "kivy\properties.pyx", line 532, in kivy.properties.Property.set
File "kivy\properties.pyx", line 1252, in kivy.properties.OptionProperty.check
The output that I am getting (which is undesirable) when i dont set any anchor value in my kivy file is as:-
I only get the floating button in the right. But the output that I desire is I wanted two floating buttons to be present on both side of the screen i.e. left as well as right. But I am getting only on one side and so i started to change the module but ended up with an error.
So, I would be glad if you can provide me an solution to solve this error so that I can use both the anchor properties 'left' and 'right'.

Related

Text displayed in debug window instead of popup window of Kivy App

I encountered some weird behavior of Kivy when trying to place the results of some analysis in a popup window of my App. By the button activation I can get a popup window (that should display the results of the analysis but is empty) and then my results are displayed in a debug window. But I'd like to see them in a popup. No error, no traceback, just weirdness.
This is how it looks like:
This is the line that runs a popup:
show_syllsoutput_popup()
This is the line that should populate it but populates debug window instead:
try: SyllOutputPopup.screen_output_label.text = cfd_syll.tabulate()
So, the question is how to put cfd_syll.tabulate() into this popup (.kv):
<SyllOutputPopup>:
FloatLayout:
Label:
id: screen_output_label
font_size: 12
pos: 100, 120
=============================================================
Alternative test: if I try to populate output popup by this:
SyllOutputPopup.screen_output_label.text = cfd_syll.tabulate()
(without try:), I get AttributeError: type object 'SyllOutputPopup' has no attribute 'screen_output_label'
Here is the full traceback, in case it'd be helpful:
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\GUI Projects\gercort\main.py", line 190, in <module>
Gercort().run()
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\app.py", line 855, in run
runTouchApp()
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\base.py", line 504, in runTouchApp
EventLoop.window.mainloop()
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\core\window\window_sdl2.py", line 747, in mainloop
self._mainloop()
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\core\window\window_sdl2.py", line 479, in _mainloop
EventLoop.idle()
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\base.py", line 342, in idle
self.dispatch_input()
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\base.py", line 327, in dispatch_input
post_dispatch_input(*pop(0))
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\base.py", line 293, in post_dispatch_input
wid.dispatch('on_touch_up', me)
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\_event.cp37-win32.pyd", line 707, in kivy._event.EventDispatcher.dispatch
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\uix\behaviors\button.py", line 179, in on_touch_up
self.dispatch('on_release')
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\_event.cp37-win32.pyd", line 703, in kivy._event.EventDispatcher.dispatch
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\_event.cp37-win32.pyd", line 1214, in kivy._event.EventObservers.dispatch
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\_event.cp37-win32.pyd", line 1098, in kivy._event.EventObservers._dispatch
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\lang\builder.py", line 64, in custom_callback
exec(__kvlang__.co_value, idmap)
File "C:\GUI Projects\gercort\gercort.kv", line 484, in <module>
on_release: root.output_toscreen(root.filepath)
File "C:\GUI Projects\gercort\main.py", line 135, in output_toscreen
SyllOutputPopup.screen_output_label.text = cfd_syll.tabulate() # populate the popup
builtins.AttributeError: type object 'SyllOutputPopup' has no attribute 'screen_output_label'
Would be grateful for any help! I don't know what parts of code would be helpful, so I apologize in advance, any suggestions are greatly appreciated.
==================================================================
Additional info:
cfd_syll is defined in the fourth line of:
def output_toscreen(сorpus_root, *args):
corpus = PlaintextCorpusReader(args[0], '.*')
cfd_syll = nltk.ConditionalFreqDist(
(textname, num_syll)
for textname in corpus.fileids()
for num_syll in [len(w) for w in ''.join(char for char in reduce_dip(corpus.raw(fileids=textname)) if char in vowels).split()])
show_syllsoutput_popup() # run the popup
try: SyllOutputPopup.screen_output_label.text = cfd_syll.tabulate() # populate the popup
except: pass
Here is the Popup class:
class SyllOutputPopup(FloatLayout):
pass
Here is definition of show_syllsoutput_popup:
def show_syllsoutput_popup():
show = SyllOutputPopup() # Create a new instance of the LicensePopup class
SyllOutputPopupWindow = Popup(title="Output", content=show, size_hint=(None,None),size=(600,400))
# Create the popup window
SyllOutputPopupWindow.open() # show the popup
In the .kv Popup is defined as:
<SyllOutputPopup>:
FloatLayout:
Label:
id: screen_output_label
font_size: 12
pos: 100, 120
screen_output_label is not the parameter of your class, it's widget's id, so that line
SyllOutputPopup.screen_output_label.text = cfd_syll.tabulate()
is wrong, you should use:
SyllOutputPopup.ids.screen_output_label.text = cfd_syll.tabulate()
==========
Also you are creating several objects of SyllOutputPopup class. You put the text in one object:
try: SyllOutputPopup.ids.screen_output_label.text = cfd_syll.tabulate()
And then you create new object, which is blank and has empty Label, and you show it:
show = SyllOutputPopup() # Create a new instance
SyllOutputPopupWindow = Popup(title="Output", content=show, size_hint=(None,None),size=(600,400))
SyllOutputPopupWindow.open()
You should use one object - set the text there and then show exactly that object, something like:
def output_toscreen(сorpus_root, *args):
corpus = PlaintextCorpusReader(args[0], '.*')
cfd_syll = nltk.ConditionalFreqDist(
(textname, num_syll)
for textname in corpus.fileids()
for num_syll in [len(w) for w in ''.join(char for char in reduce_dip(corpus.raw(fileids=textname)) if char in vowels).split()])
# that will be your object
self.sylloutputpopup = SyllOutputPopup()
self.sylloutputpopup.ids.screen_output_label.text = cfd_syll.tabulate()
show_syllsoutput_popup() # run the popup
def show_syllsoutput_popup():
show = self.sylloutputpopup
SyllOutputPopupWindow = Popup(title="Output", content=show, size_hint=(None,None),size=(600,400))
SyllOutputPopupWindow.open()
But that will work only if both of functions above are in the same class.

kivy - textinput from kv to py - import data

I'm trying to get the data from a simple textinput that is in my kv file and use the information in my python file.
but i keep getting the same error.
this error happens when i press a button and the function try to run looks like its trying to get the information from the text_location widget
thank you in advance.
class ScatterTextWidget(BoxLayout):
def initialize_request(self):
''' Initial analysis and control flow of the class '''
location = self.ids.input_location
date = S.ids.input_date
time_raw = ScatterTextWidget.ids.input_time
print(f'{location} - {date} - {time_raw}')
class HistoricalApp(App):
def build(self):
return ScatterTextWidget()
if __name__ == "__main__":
HistoricalApp().run()
the kivy file called "historical.kv"
i reduce it because is kind of long
<ScatterTextWidget>:
BoxLayout:
canvas.before:
Color:
rgb: utils.get_color_from_hex('#01183f')
Rectangle:
pos: self.pos
size: self.size
size_hint_y: None
height: 40
valign: 'middle'
TextInput:
id:text_location
width: 200
id: input2
font_size: 15
size_hint_y: None
height:40
TextInput:
id:input_date
width: 200
id: input1
font_size: 15
size_hint_y: None
height: 40
TextInput:
id:input_time
width: 200
id: input1
font_size: 15
size_hint_y: None
height: 40
the error i receive is
File "kivy\properties.pyx", line 838, in
kivy.properties.ObservableDict.__getattr__
KeyError: 'text_location'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/IBKCo/Desktop/Git Programs/TimeStationHistoricalRecords/MainGui.py", line 77, in <module>
HistoricalApp().run()
File "C:\Users\IBKCo\Desktop\Git Programs\TimeStationHistoricalRecords\pdEnv\lib\site-packages\kivy\app.py", line 826, in run
runTouchApp()
File "C:\Users\IBKCo\Desktop\Git Programs\TimeStationHistoricalRecords\pdEnv\lib\site-packages\kivy\base.py", line 502, in runTouchApp
EventLoop.window.mainloop()
File "C:\Users\IBKCo\Desktop\Git Programs\TimeStationHistoricalRecords\pdEnv\lib\site-packages\kivy\core\window\window_sdl2.py", line 727, in mainloop
self._mainloop()
File "C:\Users\IBKCo\Desktop\Git Programs\TimeStationHistoricalRecords\pdEnv\lib\site-packages\kivy\core\window\window_sdl2.py", line 460, in _mainloop
EventLoop.idle()
File "C:\Users\IBKCo\Desktop\Git Programs\TimeStationHistoricalRecords\pdEnv\lib\site-packages\kivy\base.py", line 340, in idle
self.dispatch_input()
File "C:\Users\IBKCo\Desktop\Git Programs\TimeStationHistoricalRecords\pdEnv\lib\site-packages\kivy\base.py", line 325, in dispatch_input
post_dispatch_input(*pop(0))
File "C:\Users\IBKCo\Desktop\Git Programs\TimeStationHistoricalRecords\pdEnv\lib\site-packages\kivy\base.py", line 291, in post_dispatch_input
wid.dispatch('on_touch_up', me)
File "kivy\_event.pyx", line 707, in kivy._event.EventDispatcher.dispatch
File "C:\Users\IBKCo\Desktop\Git Programs\TimeStationHistoricalRecords\pdEnv\lib\site-packages\kivy\uix\behaviors\button.py", line 179, in on_touch_up
self.dispatch('on_release')
File "kivy\_event.pyx", line 703, in kivy._event.EventDispatcher.dispatch
File "kivy\_event.pyx", line 1214, in kivy._event.EventObservers.dispatch
File "kivy\_event.pyx", line 1098, in kivy._event.EventObservers._dispatch
File "C:\Users\IBKCo\Desktop\Git Programs\TimeStationHistoricalRecords\pdEnv\lib\site-packages\kivy\lang\builder.py", line 64, in custom_callback
exec(__kvlang__.co_value, idmap)
File "C:\Users\IBKCo\Desktop\Git Programs\TimeStationHistoricalRecords\historical.kv", line 127, in <module>
on_release: root.initialize_request()
File "C:/Users/IBKCo/Desktop/Git Programs/TimeStationHistoricalRecords/MainGui.py", line 31, in initialize_request
location = self.ids.text_location
File "kivy\properties.pyx", line 841, in kivy.properties.ObservableDict.__getattr__
AttributeError: 'super' object has no attribute '__getattr__'
thank you in advance
best,
First, you need to remove both of the id:input1 lines and the id:input2 line. Then change your initialize_request method to:
def initialize_request(self):
''' Initial analysis and control flow of the class '''
location = self.ids.text_location.text
date = self.ids.input_date.text
time_raw = self.ids.input_time.text
print(f'{location} - {date} - {time_raw}')
Note that self.ids.text_location is a reference to the TextInput widget, so you have to add .text to get its text. Same for the other TextInput widgets.

Using plyer with kivy. Weird errors.

I have been trying to figure out what's wrong with this code:
from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.uix.widget import Widget
from kivy.clock import Clock
from plyer.facades import accelerometer
class Accel(Widget):
def __init__(self):
super().__init__()
self.sensorEnabled = False
def get_acceleration(self, dt):
val = accelerometer.acceleration
self.ids.label1.text = "X: " + str(val[0])
self.ids.label2.text = "Y: " + str(val[1])
self.ids.label3.text = "Z: " + str(val[2])
def pressed1(self):
try:
if not self.sensorEnabled:
# accelerometer.enable()
Clock.schedule_interval(self.get_acceleration, 1 / 20.)
self.sensorEnabled = True
self.ids.button1.text = "Stop"
else:
# accelerometer.disable()
Clock.unschedule(self.get_acceleration)
self.sensorEnabled = False
self.ids.button1.text = "Start"
except:
self.ids.status.text = "Accelerometer not supported"
class e3App(App):
def build(self):
return Accel()
if __name__ == '__main__':
e3App().run()
What happens is when I run it and press the START button it crashes and gives me this:
> Traceback (most recent call last): File
> "/usr/local/lib/python3.5/dist-packages/plyer/platforms/linux/accelerometer.py",
> line 22, in _get_acceleration
> pos = glob.glob("/sys/devices/platform/*/position")[0] IndexError: list index out of range During handling of the above
> exception, another exception occurred: Traceback (most recent call
> last): File
> "/home/rickdps/Desktop/KivyCookBook/InputMotionAndTouch/WorkingWithAccelerometer/main.py",
> line 42, in <module>
> e3App().run() File "/usr/local/lib/python3.5/dist-packages/kivy/app.py", line 828, in run
> runTouchApp() File "/usr/local/lib/python3.5/dist-packages/kivy/base.py", line 504, in
> runTouchApp
> EventLoop.window.mainloop() File "/usr/local/lib/python3.5/dist-packages/kivy/core/window/window_sdl2.py",
> line 663, in mainloop
> self._mainloop() File "/usr/local/lib/python3.5/dist-packages/kivy/core/window/window_sdl2.py",
> line 405, in _mainloop
> EventLoop.idle() File "/usr/local/lib/python3.5/dist-packages/kivy/base.py", line 339, in
> idle
> Clock.tick() File "/usr/local/lib/python3.5/dist-packages/kivy/clock.py", line 581, in
> tick
> self._process_events() File "kivy/_clock.pyx", line 367, in kivy._clock.CyClockBase._process_events
> (/tmp/pip-build-rau3eo9p/kivy/kivy/_clock.c:7700) File
> "kivy/_clock.pyx", line 397, in
> kivy._clock.CyClockBase._process_events
> (/tmp/pip-build-rau3eo9p/kivy/kivy/_clock.c:7577) File
> "kivy/_clock.pyx", line 395, in
> kivy._clock.CyClockBase._process_events
> (/tmp/pip-build-rau3eo9p/kivy/kivy/_clock.c:7498) File
> "kivy/_clock.pyx", line 167, in kivy._clock.ClockEvent.tick
> (/tmp/pip-build-rau3eo9p/kivy/kivy/_clock.c:3490) File
> "/home/rickdps/Desktop/KivyCookBook/InputMotionAndTouch/WorkingWithAccelerometer/main.py",
> line 15, in get_acceleration
> val = accelerometer.acceleration[:3] File "/usr/local/lib/python3.5/dist-packages/plyer/utils.py", line 103, in
> __getattribute__
> return getattr(object.__getattribute__(self, '_obj'), name) File
> "/usr/local/lib/python3.5/dist-packages/plyer/facades/accelerometer.py",
> line 44, in acceleration
> return self.get_acceleration() File "/usr/local/lib/python3.5/dist-packages/plyer/facades/accelerometer.py",
> line 60, in get_acceleration
> return self._get_acceleration() File "/usr/local/lib/python3.5/dist-packages/plyer/platforms/linux/accelerometer.py",
> line 24, in _get_acceleration
> raise Exception('Could not enable accelerometer!') Exception: Could not enable accelerometer!
I am following this book called "Kivy Cook Book", and I've mostly copied and pasted code in order to try it. This one has not worked though.
I'd really appreciate any help.

Kivy - How to access kivy widget in python?

I want to edit a text in a TextInput in kivy but don't know how to, I've tried this code as Ive search in the net but still no luck.
class MainApp(Screen):
def __init__(self,**kwargs):
super(MainApp,self).__init__(**kwargs)
pass
class Forms(BoxLayout):
def __init__(self, **kwargs):
super(Main,self).__init__(**kwargs)
self.ids.txtSearch.text = "new text"
class Main(App):
def build(self):
return root_widget
if __name__ == "__main__":
Main().run()
------kivy-------
<Main>:
TextInput:
id: txtSearch
this is not my whole code but I think those are what matters in the issue
this is the error:
File "C:\Users\Guest\Documents\Python\Kivy\Project\main.py", line 295, in <module>
''')
File "D:\Kivy-1.9.0-py3.4-win32-x64\kivy34\kivy\lang.py", line 1828, in load_string
self._apply_rule(widget, parser.root, parser.root)
File "D:\Kivy-1.9.0-py3.4-win32-x64\kivy34\kivy\lang.py", line 1985, in _apply_rule
self.apply(child)
File "D:\Kivy-1.9.0-py3.4-win32-x64\kivy34\kivy\lang.py", line 1872, in apply
self._apply_rule(widget, rule, rule)
File "D:\Kivy-1.9.0-py3.4-win32-x64\kivy34\kivy\lang.py", line 1986, in _apply_rule
self._apply_rule(child, crule, rootrule)
File "D:\Kivy-1.9.0-py3.4-win32-x64\kivy34\kivy\lang.py", line 1986, in _apply_rule
self._apply_rule(child, crule, rootrule)
File "D:\Kivy-1.9.0-py3.4-win32-x64\kivy34\kivy\lang.py", line 1983, in _apply_rule
child = cls(__no_builder=True)
File "C:\Users\Guest\Documents\Python\Kivy\Project\main.py", line 40, in __init__
self.ids.txtSearch.text = "new text"
File "kivy\properties.pyx", line 720, in kivy.properties.ObservableDict.__getattr__ (kivy\properties.c:10911)
AttributeError: 'super' object has no attribute '__getattr__'
To change Widgets properties in kivy you need to 'link' the widget between .py and .kv file, first in .py file:
txt_Search = ObjectProperty()
then in .kv file, in your root widget:
txt_Search: txtSearch
then assign the id to a widget (as you already did):
<Main>:
TextInput:
id: txtSearch
text: ' '
then in your .py file, you can change attributes of the widget by doing this:
self.txt_Search.text = 'New Text'
or any other attribute:
self.txt_Search.height = '30dp'
Are you sure self.ids.txtSearch exists when you try to assign a text to it? You're calling super(Main,self) one line above so I guess txtSearch is never instantiated.
Btw, it's better to init widgets in *.kv files:
<Main>:
TextInput:
id: txtSearch
text: "new text"

TypeError for pickle of array of custom objects in Python

I have the following method:
def save(self):
vertices = self.mindmap.get_vertices()
edges = self.mindmap.get_edges()
output = open('mindmap.pkl', 'wb')
pickle.dump(edges, output)
pickle.dump(vertices, output)
output.close()
When I call this method, I get the following error:
Traceback (most recent call last):
File "main.py", line 72, in <module>
MindMapApp().run()
File "/Applications/Kivy.app/Contents/Resources/kivy/kivy/app.py", line 792, in run
runTouchApp()
File "/Applications/Kivy.app/Contents/Resources/kivy/kivy/base.py", line 481, in runTouchApp
EventLoop.window.mainloop()
File "/Applications/Kivy.app/Contents/Resources/kivy/kivy/core/window/window_pygame.py", line 381, in mainloop
self._mainloop()
File "/Applications/Kivy.app/Contents/Resources/kivy/kivy/core/window/window_pygame.py", line 287, in _mainloop
EventLoop.idle()
File "/Applications/Kivy.app/Contents/Resources/kivy/kivy/base.py", line 324, in idle
self.dispatch_input()
File "/Applications/Kivy.app/Contents/Resources/kivy/kivy/base.py", line 309, in dispatch_input
post_dispatch_input(*pop(0))
File "/Applications/Kivy.app/Contents/Resources/kivy/kivy/base.py", line 275, in post_dispatch_input
wid.dispatch('on_touch_up', me)
File "_event.pyx", line 316, in kivy._event.EventDispatcher.dispatch (kivy/_event.c:4537)
File "/Applications/Kivy.app/Contents/Resources/kivy/kivy/uix/behaviors.py", line 110, in on_touch_up
self.dispatch('on_release')
File "_event.pyx", line 312, in kivy._event.EventDispatcher.dispatch (kivy/_event.c:4491)
File "/Applications/Kivy.app/Contents/Resources/kivy/kivy/lang.py", line 1299, in custom_callback
exec(__kvlang__.co_value, idmap)
File "./mindmap.kv", line 14, in <module>
on_release: app.save()
File "main.py", line 27, in save
pickle.dump(vertices, output)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1370, in dump
Pickler(file, protocol).dump(obj)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 224, in dump
self.save(obj)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 600, in save_list
self._batch_appends(iter(obj))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 615, in _batch_appends
save(x)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 306, in save
rv = reduce(self.proto)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy_reg.py", line 71, in _reduce_ex
state = base(self)
TypeError: __init__() takes exactly 0 positional arguments (1 given)
I do not get this error if both arrays are empty. When the above was generated edges was empty and vertices had a size of one. I really don't know how to interpret this error, and as such have no idea how to resolve it.
This is my Vertex class __init__:
def __init__(self, pos=None, size=None):
super(Vertex, self).__init__()
self.pos = pos
self.size = size
if self.height < self.MINIMUM_HEIGHT + self.TEXT_OFFSET:
self.height = self.MINIMUM_HEIGHT + self.TEXT_OFFSET
if self.width < self.MINIMUM_WIDTH + self.TEXT_OFFSET:
self.width = self.MINIMUM_WIDTH + self.TEXT_OFFSET
self.originalSize = self.size
self.originalWidth = self.size[0]
self.newIdea = TextInput(
height = self.MINIMUM_HEIGHT,
size_hint = (None, None),
pos_hint = {'center_x':.5, 'center_y':.5},
background_active = '',
background_normal = '',
use_bubble = True,
foreground_color = (.4, .4, .4, 1),
cursor_color = (.4, .4, .4, 1))
self.newIdea.bind(text=self.on_text)
self.idea = Label(
height = self.MINIMUM_HEIGHT,
size_hint = (None, None),
pos_hint = {'center_x':.5, 'center_y':.5},
color = (.4, .4, .4,1))
Logger.info('Vertex: created')
Indeed, the Kivy EventDispatcher object is at fault here; the object.__reduce_ex__ method searches for the first baseclass that is not a custom class (it does not have the Py_TPFLAGS_HEAPTYPE flag set), to call __init__ on that class. This fails for that base class, as it's __init__ method doesn't support passing in a single argument.
The work-around is to use the latest pickle protocol instead; it uses a different codepath:
pickle.dump(edges, output, pickle.HIGHEST_PROTOCOL)
pickle.dump(vertices, output, pickle.HIGHEST_PROTOCOL)
because the latest pickle protocol (2) supports new-style classes much more efficiently.
Seeing the complexity of the Kivy object hierarchy, you may need to customise the pickling process.
I'd look into implementing the __getnewargs__ method for example:
def __getnewargs__(self):
return (self.pos, self.size)
would ensure that just that data is pickled, nothing more. On unpickling, these two values are then used to create new Vertex objects. Note that for this method to be used you have to use the latest protocol!
You could also implement a __getstate__ method; if you return a dictionary, no mirror __setstate__ method is required, but would allow you to initialise some more attributes.
If neither is implemented, the contents of the instance __dict__ is pickled instead. Make sure that everything contained can be pickled.

Categories

Resources