I have some problems with rewriting python code in kivy format
Here is the class "Settings" which has method to change screen.
class SettingsMenu(Screen):
def on_touch_down(self, touch):
if touch.button == 'right':
self.parent.transition.direction = "right"
self.parent.transition.duration = 0.6
self.parent.current = "MainMenu"
And I want to rewrite it in kivy this way (or something like that):
<SettingsMenu>
name: "SettingsMenu"
on_touch_down:
if button == "right":
root.parent.transition.direction = "right"
root.parent.transition.duration = 0.6
root.parent.current = "MainMenu"
How should I do it correctly?
(Edit) Here is the full code. I just create two screens and when we are on SettingsMenu screen, I want to switch back to MainMenu screen with right mouse button
(Commented on_touch_down in SettingsMenu python class works correctly, but when I try to make it in kivy way, I switch the screen with any mouse button, but desired was right mouse button)
Python:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.config import Config
Config.set('input', 'mouse', 'mouse,multitouch_on_demand')
class MainMenu(Screen):
pass
class SettingsMenu(Screen):
pass
# def on_touch_down(self, touch):
# if touch.button == 'right':
# self.parent.transition.direction = "right"
# self.parent.transition.duration = 0.6
# self.parent.current = "MainMenu"
class MenuManager(ScreenManager):
pass
main_kv = Builder.load_file("test.kv")
class THEApp(App):
def build(self):
return main_kv
THEApp().run()
This is the Kivy file (indentation may be broken during copy-paste, but I had no problems with syntax):
MenuManager:
MainMenu:
SettingsMenu:
<MainMenu>
name: "MainMenu"
FloatLayout:
size: root.width, root.height
Button:
text: "Button 1 on Main Menu Screen"
on_release:
root.manager.transition.direction = 'left'
root.manager.transition.duration = 0.6
root.manager.current = "SettingsMenu"
<SettingsMenu>
name: "SettingsMenu"
button: "right"
on_touch_down:
if root.button == "right": \
root.parent.transition.direction = "right"; \
root.parent.transition.duration = 0.6; \
root.parent.current = "MainMenu"
FloatLayout:
size: root.width, root.height
Label:
text: "Label 1 on SettingsMenu"
You can do python code/logic for an on_touch_down:
attribute in a kv
file, but it is a bit goofy. I think your kv
file will work like this:
<SettingsMenu>
name: "SettingsMenu"
on_touch_down:
if args[1].button == "right": \
root.parent.transition.direction = "right"; \
root.parent.transition.duration = 0.6; \
root.parent.current = "MainMenu"
In the kivy
language, you can access the args
of an on_<action>
method (see documentation). So the code above checks the button
attribute of the touch
arg.
Note that the if
statement in the kv
file must be on a single line. That is the reason for the \
characters (to escape endlines) and the ;
(to delimit the lines of code).