Implement android back button function in Kivy - kivy

Firstly, i have gone thru many examples, but could not figure out this, so asking here.
My app is to be run on android. Screen 1 have a button which will go to screen 2 on click.
All i need is code to move back to screen 1 on pressing back button on screen 2
My code:
#!/usr/bin/kivy
import kivy
kivy.require('1.7.2')
from random import random
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from random import random
from random import choice
from kivy.properties import StringProperty
import time
from kivy.clock import Clock
from functools import partial
from kivy.utils import platform
from kivy.core.window import Window
Builder.load_string("""
<MenuScreen>:
Button:
text: "move to next screen 2"
on_press: root.manager.current = 'game_mode'
<GameMode>:
Label:
text: "screen 2"
""")
class MenuScreen(Screen):
pass
class GameMode(Screen):
pass
sm = ScreenManager()
menu_screen = MenuScreen(name='menu')
sm.add_widget(menu_screen)
sm.add_widget(GameMode(name='game_mode'))
class TestApp(App):
def build(self):
self.bind(on_start=self.post_build_init)
return sm
def post_build_init(self,ev):
if platform == 'android':
import android
android.map_key(android.KEYCODE_BACK, 1001)
win = Window
win.bind(on_keyboard=self.key_handler)
def key_handler(self, window, keycode1, keycode2, text, modifiers):
if keycode1 == 27 or keycode1 == 1001:
sm.go_back()
return True
return False
if __name__ == '__main__':
TestApp().run()
Please help. I want solution based on screen manager. I would really appreciate if you can improve my code to provide solution.

Finally, figured it out
#!/usr/bin/kivy
import kivy
kivy.require('1.7.2')
from random import random
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from random import random
from random import choice
from kivy.properties import StringProperty
import time
from kivy.clock import Clock
from functools import partial
from kivy.core.window import Window
Builder.load_string("""
<MenuScreen>:
Button:
text: "move to next screen 2"
on_press: root.manager.current = 'game_mode'
<GameMode>:
Label:
text: "screen 2"
""")
class MenuScreen(Screen):
pass
class GameMode(Screen):
pass
sm = ScreenManager()
menu_screen = MenuScreen(name='menu')
sm.add_widget(menu_screen)
sm.add_widget(GameMode(name='game_mode'))
class TestApp(App):
def build(self):
self.bind(on_start=self.post_build_init)
return sm
def post_build_init(self,ev):
from kivy.base import EventLoop
EventLoop.window.bind(on_keyboard=self.hook_keyboard)
def hook_keyboard(self, window, key, *largs):
if key == 27:
print sm.current
if(sm.current=='menu'):
App.get_running_app().stop()
sm.current='menu'
return True
if __name__ == '__main__':
TestApp().run()

ScreenManager has a previous() method that should solve your problem:
Builder.load_string("""
<MenuScreen>:
Button:
text: "move to next screen 2"
on_press: root.manager.current = 'game_mode'
<GameMode>:
BoxLayout:
orientation: "vertical"
Button:
text: "go back"
on_press: root.manager.current = root.manager.previous()
Label:
text: "screen 2"
""")

Related

Since the rectangle is not a button, then how can I create a callback function to print('something') after clicking on that rectangle?

I have a rectangle in a canvas. Since the rectangle is not a button, then how can I create a callback function to print('something') after clicking on that rectangle?
In a button I can use on_release to call a function, but in rectangle how should I call a function after clicking on that rectangle?
import kivy
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.widget import Widget
#from kivy.graphics import *
from kivy.core.window import Window
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.animation import Animation
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.clock import Clock
Builder.load_string('''
<main>:
RelativeLayout :
size: root.width,root.height
canvas:
Color:
rgba:196/255, 195/255, 49/255,1
Rectangle:
size:470,root.height
''')
class main(Screen):
pass
class test(App):
def build(self):
sm = sm = ScreenManager()
sm.add_widget(main(name='main'))
Window.clearcolor=(55/255, 77/255, 33/255)
return sm
if __name__=='__main__':
test().run()

how can i get the image property that is in .kv file and change the size in .py file

my python code is:
from kivy.app import App
from kivy.lang import Builder
from kivymd.theming import ThemeManager
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
login=Builder.load_file('login.kv')
class Login(BoxLayout):
imge=ObjectProperty()
def press(self):
self.imge.size_hint=(.2,.2)
class Main(App):
def build(self):
theme_cls=ThemeManager()
return Login()
if __name__=="__main__":
Main().run()
my .kv file is:
<Login>:
imge:img
Image:
id:img
source:'22.png'
Button:
text:"click"
on_press:root.press()
i need to change the image size on click button,but the Objectproperty is not providing the image properties
So first of all you it is better using a boylayout when you want to use size_hints But it is your wish. In your case you have to give your image also size_hints
from kivy.app import App
from kivy.lang import Builder
from kivymd.theming import ThemeManager
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
login=Builder.load_file('login.kv')
class Login(BoxLayout):
image = ObjectProperty()
def press(self):
self.image.size_hint = (.2,.5)
class Main(App):
def build(self):
return Login()
if __name__=="__main__":
Main().run()
kv file:
<Login>:
image:img
Image:
size_hint:.5,1
id:img
source:'play.png'
Button:
text:"click"
size_hint:.2,.1
on_release:
root.press()
With FloatLayout. When using boxlayout the button will also increase the size. So floatlayout is better
from kivy.app import App
from kivy.lang import Builder
from kivymd.theming import ThemeManager
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
login=Builder.load_file('login.kv')
class Login(FloatLayout):
image = ObjectProperty()
def press(self):
self.image.size_hint = (.2,.5)
class Main(App):
def build(self):
return Login()
if __name__=="__main__":
Main().run()
and kv file
<Login>:
image:img
Image:
size_hint:.5,1
id:img
source:'play.png'
Button:
text:"click"
size_hint:.2,.1
on_release:
root.press()
So check the effect with box and floatlayouts. Ur problem was u did not give the image size_hints in kv file

How to use random with button in Kivy

I just want to have 2 buttons in my KIVY APP.
One with text "Hello" and other having a random number from 0-9.
My code
#!/usr/bin/kivy
import kivy
kivy.require('1.7.2')
from random import random
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from random import random
Builder.load_string("""
<Highest>:
r1c1: "hello"
r1c2: random.randrange(10)
GridLayout:
cols: 1
Button:
text: root.r1c1
Button:
text: root.r1c2
""")
class Highest(Screen):
pass
# Create the screen manager
sm = ScreenManager()
sm.add_widget(Highest(name='Highest'))
class TestApp(App):
def build(self):
return sm
if __name__ == '__main__':
TestApp().run()
My code works if I just have one button with text - Hello. Random seems not working.
Perhaps it's because randrange isn't returning a string, but an int. You could try:
r1c2: str(random.randrange(10))
OR
Try adding it as a function to your root widget:
class Highest(Screen):
def get_rand(self):
return str(random.randrange(10))
And your kv would look like this:
r1c2: root.get_rand()

How to change popup label in kivy

My application appends a variable score by one on each click. I want to display a popup after each click to show score.
My attempt:
#!/usr/bin/kivy
import kivy
kivy.require('1.7.2')
from random import random
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from random import random
from random import choice
from kivy.properties import StringProperty
import time
score=0
my_popup = Popup(title='Test popup',
content=Label(text=str(score)),
size_hint=(None, None))
Builder.load_string("""
<Highest>:
GridLayout:
cols: 1
Button:
id: btn_0
text: "0"
on_press: root.new()
Label:
""")
class Highest(Screen):
def new(self):
global score
score=score+1
self.ids['btn_0'].text = str(score)
my_popup.open()
# Create the screen manager
sm = ScreenManager()
sm.add_widget(Highest(name='Highest'))
class TestApp(App):
def build(self):
return sm
if __name__ == '__main__':
TestApp().run()
However, score is always displayed as 0. Score is increasing correctly and can be seen on button text.
You would probably need to define my_popup as a function with score as argument:
def my_popup(updated_score):
pop = Popup(title='Test popup', content=Label(text=str(updated_score)),
size_hint=(None,None))
pop.open()
Then call it at function "new" passing the updated score:
class Highest(Screen):
def new(self):
global score
score += 1
self.ids['btn_0'].text = str(score)
my_popup(score)

Change button text value for on_press event in Kivy

My application has a single button with text value as '2'. I want to change the text value to 100 on on_press event
My attempt:
#!/usr/bin/kivy
import kivy
kivy.require('1.7.2')
from random import random
from random import choice
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
r1c2=random()
Builder.load_string("""
<Highest>:
r1c2: str(2)
GridLayout:
cols: 1
Button:
text: root.r1c2
on_press: root.new()
""")
class Highest(Screen):
def new(self):
r1c2=str(100)
# Create the screen manager
sm = ScreenManager()
sm.add_widget(Highest(name='Highest'))
class TestApp(App):
def build(self):
return sm
if __name__ == '__main__':
TestApp().run()
Error: Currently, nothing happens when the button is pressed. Please help
You should be using kivy properties available. See kivy.properties for more information.
Add this import for access to string property:
from kivy.properties import StringProperty
And your Highest class should be:
class Highest(Screen):
r1c2 = StringProperty(str(2))
def new(self):
self.r1c2 = str(100)
At initialization r1c2 value is equal to '2'. When the function new() is called value of r1c2 will become '100'. Button text is bind to the string property r1c2 so it will automatically change.
You don't need r1c2=str(2) in your builder string.
Builder.load_string("""
<Highest>:
GridLayout:
cols: 1
Button:
text: root.r1c2
on_press: root.new()
""")

Resources