Question regarding changing screens in KivyMD - python

I'm new to KIVYMD and have been trying to play around by creating a log in screen that transfers the user to a new page. I've gotten making the core of the screen down, like adding the textfields and buttons, but am not sure how I can implement a screen changing functionality to my code. Any help is greatly appreciated.
For reference here is my main code block:
from kivymd.app import MDApp
from kivy.lang.builder import Builder
from helpers import username_helper,password_helper
from kivy.uix.screenmanager import Screen
from kivymd.uix.button import MDRectangleFlatButton
class Demo_app(MDApp):
def build(self):
screen = Screen()
self.theme_cls.primary_palette= "Pink"
self.username= Builder.load_string(username_helper)
screen.add_widget(self.username)
self.password = Builder.load_string(password_helper)
screen.add_widget(self.password)
login = MDRectangleFlatButton(text="Log In", pos_hint={"center_x": 0.5, "center_y":0.4})
screen.add_widget(login)
signin = MDRectangleFlatButton(text="Sign Up", pos_hint={"center_x": 0.5, "center_y": 0.3})
screen.add_widget(signin)
return screen
Demo_app().run()
And here is my .kv file:
username_helper="""
MDTextField:
hint_text: "Create/Enter your Username"
helper_text:"Or click here if you forgot your Username"
helper_text_mode: "on_focus"
icon_right: "language-python"
icon_right_color: app.theme_cls.primary_color
pos_hint:{"center_x":0.5,"center_y":0.6}
size_hint_x:None
width:300
"""
password_helper="""
MDTextField:
hint_text: "Create/Enter your Password"
helper_text:"Or click here if you forgot your password "
helper_text_mode: "on_focus"
icon_right: "language-python"
icon_right_color: app.theme_cls.primary_color
pos_hint:{"center_x":0.5,"center_y":0.5}
size_hint_x:None
width:300
"""

I think you want to transfer those textinput data to a label in different class. I think this is what you need.(keep an eye on ids):
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.label import Label
from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition
class FirstPage(FloatLayout):
def switch_screen(self):
secondpage = self.login_name = self.ids.login_name.text
myapp.secondpage.update_name1(secondpage)
secondpage = self.password_name = self.ids.password_name.text
myapp.secondpage.update_name2(secondpage)
myapp.screen_manager.transition = SlideTransition(direction='left', duration=.25)
myapp.screen_manager.current = 'SecondPage'
class SecondPage(FloatLayout):
def switch_back(self):
myapp.screen_manager.transition = SlideTransition(direction='right', duration=.25)
myapp.screen_manager.current = 'FirstPage'
def update_name1(self, name_login):
self.ids.name_login.text = (f'{name_login}:')
def update_name2(self, name_password):
self.ids.name_password.text = (f'{name_password}:')
class MyApp(App):
def build(self):
self.screen_manager = ScreenManager()
self.firstpage = FirstPage()
screen = Screen(name='FirstPage')
screen.add_widget(self.firstpage)
self.screen_manager.add_widget(screen)
self.secondpage = SecondPage()
screen = Screen(name='SecondPage')
screen.add_widget(self.secondpage)
self.screen_manager.add_widget(screen)
return self.screen_manager
myapp = MyApp()
myapp.run()
Here's kivy code:
FirstPage:
<FirstPage>:
TextInput:
id: login_name
size_hint: .65, .08
multiline: False
font_size: 20
pos_hint: {'x': .2, 'y': .57}
TextInput:
id: password_name
size_hint: .65, .08
multiline: False
font_size: 20
pos_hint: {'x': .2, 'y': .47}
Button:
text: "First"
size_hint: .1, .1
on_release: root.switch_screen()
<SecondPage>:
Button:
text: "Second"
size_hint: .1, .1
on_release: root.switch_back()
Label:
id: name_login
text: "Login"
size_hint: .2, .2
pos_hint: {'x': .2, 'y': .57}
Label:
id: name_password
text: "Password"
size_hint: .2, .2
pos_hint: {'x': .2, 'y': .47}

Related

I can't switch screen in kivy

I followed a tutorial on youtube so I could learn how to use kivy, but when I try to switch screen it doesn't work, I write my code the exact same way the guy does it, but for some reason nothing happens when I click the button "Se dine produkter".
I have written where I need help in the .kv file, I added the rest of the code only in case if you need to know why I have done certain things. In line 10 and 25 I have written what I want to happen, I have tried so many different things and different ways to approach what I want, but I haven't succeed with any of them.
main.py:
import kivy
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.popup import Popup
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
Builder.load_file("struktur.kv")
class HovedVindu(Screen and Widget):
def nyttProdukt(self):
show_popup()
def dineProdukter(self):
print("dine produkter")
ScreenManager.current = "dineprodukter"
def leggTilNyttProdukt(self, navn, dato):
self.navn = navn
self.dato = dato
print(self.navn, self.dato)
class DineProdukter(Screen):
pass
class WindowManager(ScreenManager):
pass
class P(FloatLayout):
pass
class MainApp(App):
def build(self):
return HovedVindu()
def show_popup():
show = P()
popupWindow = Popup(title="Legg til ett nytt produkt", content=show, size_hint=(None,None),size=(400,400), title_align="center")
popupWindow.open()
if __name__ == "__main__":
MainApp().run()
struktur.kv:
#:kivy 2.1.0
<WindowManager>:
HovedVindu:
DineProdukter:
<DineProdukter>:
name: "dineprodukter"
Button:
text: "Go to main"
on_release: switch to (hoved)
<HovedVindu>:
name: "hoved"
FloatLayout:
Button:
text: "Nytt produkt"
size_hint: 2, 1
pos_hint: {"x": 3, "top": 5}
on_release: root.nyttProdukt()
Button:
text: "Se dine produkter"
size_hint: 2, 1
pos_hint: {"x": 3, "top": 3}
on_release: switch to (dineprodukter)
<P>:
TextInput:
hint_text: "Navnet på produktet"
size_hint: .6, .15
pos_hint: {"x": .2, "top": .9}
TextInput:
hint_text: "Siste forbruksdag"
size_hint: .6, .15
pos_hint: {"x": .2, "top": .7}
Button:
text: "Legg til produkt"
size_hint: 0.8, 0.2
pos_hint: {"x":0.1, "y":0.1}
It happens because you are actually not using Screen Manager.
Please follow official kivy documentation on how to use ScreenManager.
https://kivy.org/doc/stable/api-kivy.uix.screenmanager.html
Example code of build function using ScreenManager:
def build(self) -> ScreenManager:
self.sm = ScreenManager()
self.sm.add_widget(SplashScreen(name='splash_screen'))
self.sm.add_widget(DownloadScreen(name='download_screen'))
self.sm.add_widget(InfoScreen(name='info_screen'))
self.sm.add_widget(FileManager(name='file_manager'))
return self.sm
Example usage in .kv file:
MDFillRoundFlatIconButton:
text: 'Download'
icon: 'download'
pos_hint: {'x': 0.77, 'y': 0.01}
md_bg_color: 64/255, 120/255, 192/255, 1
on_press:
root.manager.transition.direction = 'right'
root.manager.current = 'download_screen'
There is some other ways to do it, but I don't think your code is exactly the same as the code of the guy from YouTube. Stick to kivy documentation, it is actually good and you will learn 'kivy ways' of doing things.
Using switch_to(screen_name) not switch to(screen_name) won't work either if you won't use instance of your Screen Manager. Without that is just non existing function.
Here please you have your code fixed up a bit:
import kivy
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.popup import Popup
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
Builder.load_file("struktur.kv")
class HovedVindu(Screen):
def nyttProdukt(self):
show_popup()
def dineProdukter(self):
print("dine produkter")
ScreenManager.current = "dineprodukter"
def leggTilNyttProdukt(self, navn, dato):
self.navn = navn
self.dato = dato
print(self.navn, self.dato)
class DineProdukter(Screen):
pass
class P(FloatLayout):
pass
class MainApp(App):
def build(self):
sm = ScreenManager()
sm.add_widget(HovedVindu(name="hoved"))
sm.add_widget(DineProdukter(name="dineprodukter"))
return sm
def show_popup():
show = P()
popupWindow = Popup(title="Legg til ett nytt produkt", content=show, size_hint=(None,None),size=(400,400), title_align="center")
popupWindow.open()
if __name__ == "__main__":
MainApp().run()
And kivy file:
#:kivy 2.1.0
<DineProdukter>:
FloatLayout:
Button:
text: "Go to main"
pos_hint: {"center_x": .5, "center_y": .5}
size_hint: .2, .2
on_release: root.manager.current = "hoved"
<HovedVindu>:
FloatLayout:
Button:
text: "Nytt produkt"
size_hint: .3, .1
pos_hint: {"x": .7, "y": .5}
on_release: root.nyttProdukt()
Button:
text: "Se dine produkter"
size_hint: .3, .1
pos_hint: {"x": .3, "y": .5}
on_release: root.manager.current = "dineprodukter"
<P>:
TextInput:
hint_text: "Navnet på produktet"
size_hint: .6, .15
pos_hint: {"x": .2, "top": .9}
TextInput:
hint_text: "Siste forbruksdag"
size_hint: .6, .15
pos_hint: {"x": .2, "top": .7}
Button:
text: "Legg til produkt"
size_hint: 0.8, 0.2
pos_hint: {"x":0.1, "y":0.1}
Haven't done everything but it displays screens and buttons do work.
I have kicked out your class of ScreenManager and actually created an instance of it in the root of your app. That way you can call it from any screen, as they are added to the Manager. Like you need to give screens to the Manager before it can manage it. That way always works fine and you won't experience any problems even if your app will contain 20 or more different classes with screens.

OCR using Kivy and Screenmanager issue passing variable between screens

I am building an OCR application for visually impaired users. I'm wanting the app to open straight away onto the camera screen, when the user takes a pic on button press I want ocr process to occur and display the output on the text screen in a lbl or txtbox and have a TTS read out what the text says. My issue is that i am having trouble obtaining the output of ocr and displaying it, I'm not familiar with screenmanager or python. ideally the opencv and tesseract process would occur in same function as the capture however i cant get the output recognised on the following screen. heres some code, any suggestions and help appreciated!
# Importing the libraries
import cv2
import pytesseract
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen
pytesseract.pytesseract.tesseract_cmd = r'D:/pytesseract/tesseract.exe'
# voice_text = ""
# for i in ocrtext.split():
# voice_text += i + ' '
# voice_text = voice_text[:-1]
# voice_text
# engine = pyttsx3.init()
# engine.setProperty("rate", 145)
# voices = engine.getProperty('voices')
# engine.setProperty('voice', voices[0].id)
# engine.say(voice_text)
# engine.runAndWait()
class CameraScreen(Screen):
def capture(self):
camera = self.ids['camera']
camera.export_to_png("./picforocr.png")
image = cv2.imread("./picforocr.png")
ocrtext = pytesseract.image_to_string(image)
class TextScreen(Screen):
pass
GUI = Builder.load_string("""
GridLayout:
cols: 1
ScreenManager:
id: screen_manager
CameraScreen:
name: "camera_screen"
id: camera_screen
TextScreen:
name: "text_screen"
id: text_screen
<CameraScreen>:
orientation: 'vertical'
GridLayout:
cols: 1
Camera:
id: camera
resolution: (800, 800)
Button:
text: 'OCR!'
size_hint_y: None
height: '48dp'
on_press:
root.capture()
# root refers to <CameraScreen>
# app refers to TestCamera, app.root refers to the GridLayout: at the top
app.root.ids['screen_manager'].transition.direction = 'left'
app.root.ids['screen_manager'].current = 'text_screen'
<TextScreen>:
Label:
id: ocr_output
text:
Camerascreen.ocrtext
font_size: 20
Button:
text: "Do OCR Again"
size_hint_y: None
height: '48dp'
font_size: 50
on_press:
app.root.ids['screen_manager'].transition.direction = 'right'
app.root.ids['screen_manager'].current = 'camera_screen'
""")
class MyOCRApp(App):
def build(self):
return GUI
if __name__ == "__main__":
MyOCRApp().run()
This is basic code for passing texts from one class to another and also TextInput data. This is python code:
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.label import Label
from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition
class FirstPage(FloatLayout):
def switch_screen(self):
secondpage = self.login_name = self.ids.login_name.text
myapp.secondpage.update_name1(secondpage)
secondpage = self.password_name = self.ids.password_name.text
myapp.secondpage.update_name2(secondpage)
myapp.screen_manager.transition = SlideTransition(direction='left', duration=.25)
myapp.screen_manager.current = 'SecondPage'
class SecondPage(FloatLayout):
def switch_back(self):
myapp.screen_manager.transition = SlideTransition(direction='right', duration=.25)
myapp.screen_manager.current = 'FirstPage'
def update_name1(self, name_login):
self.ids.name_login.text = (f'{name_login}:')
def update_name2(self, name_password):
self.ids.name_password.text = (f'{name_password}:')
class MyApp(App):
def build(self):
self.screen_manager = ScreenManager()
self.firstpage = FirstPage()
screen = Screen(name='FirstPage')
screen.add_widget(self.firstpage)
self.screen_manager.add_widget(screen)
self.secondpage = SecondPage()
screen = Screen(name='SecondPage')
screen.add_widget(self.secondpage)
self.screen_manager.add_widget(screen)
return self.screen_manager
myapp = MyApp()
myapp.run()
And this is kivy code:
FirstPage:
<FirstPage>:
TextInput:
id: login_name
size_hint: .65, .08
multiline: False
font_size: 20
pos_hint: {'x': .2, 'y': .57}
TextInput:
id: password_name
size_hint: .65, .08
multiline: False
font_size: 20
pos_hint: {'x': .2, 'y': .47}
Button:
text: "First"
size_hint: .1, .1
on_release: root.switch_screen()
<SecondPage>:
Button:
text: "Second"
size_hint: .1, .1
on_release: root.switch_back()
Label:
id: name_login
text: "Login"
size_hint: .2, .2
pos_hint: {'x': .2, 'y': .57}
Label:
id: name_password
text: "Password"
size_hint: .2, .2
pos_hint: {'x': .2, 'y': .47}

How do I make a dropdown menu in KivyMD, Python

Hi I was wondering how to make a dropdown menu and I cant figure it out I have read the documentation but I do not understand so I would be grateful if someone told my the problem with my attempt at is in my code.
PYTHON FILE:
from kivymd.app import MDApp
from kivymd.uix.screen import Screen
from kivymd.uix.button import MDRectangleFlatButton, MDRoundFlatButton
from kivymd.uix.textfield import MDTextField
from kivy.lang import Builder
from kivymd.uix.menu import MDDropdownMenu
from kivy.metrics import dp
from kivy.properties import StringProperty
from kivymd.uix.list import OneLineIconListItem
class IconListItem(OneLineIconListItem):
icon = StringProperty()
class DemoApp(MDApp):
def show_data(self):
inputFahrenheit = self.root.ids.fahrenheit.text
print(inputFahrenheit)
def fahrenheitSelected(self):
fahrenheit = True
celsius = False
def on_start(self):
self.theme_cls.primary_palette = "Green"
self.theme_cls.primary_hue = "A700"
self.theme_cls.theme_style = "Light"
self.dropdown1 = MDDropdownMenu()
self.dropdown1.items.append(
{"viewclass": "MDMenuItem",
"text": "option1",
"callback": self.callback()}
)
def callback(self):
print("cookies")
def build(self):
kv = Builder.load_file("test.kv")
screen = Screen()
return kv
DemoApp().run()
KV FILE:
Screen:
MDTextField:
id: fahrenheit
hint_text:"Enter Fahrenheit"
helper_text: "Once you enter the fahrenheit the press submit"
helper_text_mode: "on_focus"
icon_right: "temperature-fahrenheit"
pos_hint: {'center_x': 0.5, 'center_y': 0.9}
size: 200, 25
size_hint: None, None
MDRoundFlatButton:
text: "Enter"
pos_hint: {'center_x': 0.5, 'center_y': 0.2}
text_color: 0, 1, 0, 1
size_hint: 0.25, 0.20
on_release: app.show_data()
MDIconButton:
icon: "language-python"
pos_hint: {"center_x": .5, "center_y": .5}
on_release: app.dropdown.open(root)
I don't know what is going on hear so I would appreciate it if someone knew the answer and posted it here.
I do not know what this class is - "MDMenuItem", you did not present it in your example, but as I understood you want to use it in the list menu, so I specified OneLineListItem as a viewclass, the list does not have a callback method (and in general it does not exist in almost all kivy classes), instead you should use on_release or on_press as in my example. If you do not want to use lambda, then you do not need to explicitly call the function - "on_release": self. callback. Also, to access some object of the class (in your example, it is MDDropdownMenu), it must be defined in __init__. Also, menu_items should be a list, not a dictionary as in your example, read the documentation carefully. You also forgot to specify the caller argument of the MDDropdownMenu class. I also noticed that you have the IconListItem class, but you don't use it anywhere, so I deleted it, if you want to create a list with icons, see this. And you should not specify the definition of the theme and color in the examples, this does not affect anything.
from kivymd.app import MDApp
from kivymd.uix.menu import MDDropdownMenu
from kivy.properties import StringProperty
from kivy.lang import Builder
KV = """
Screen:
MDTextField:
id: fahrenheit
hint_text:"Enter Fahrenheit"
helper_text: "Once you enter the fahrenheit the press submit"
helper_text_mode: "on_focus"
icon_right: "temperature-fahrenheit"
pos_hint: {'center_x': 0.5, 'center_y': 0.9}
size: 200, 25
size_hint: None, None
MDRoundFlatButton:
text: "Enter"
pos_hint: {'center': (0.5,0.2)}
text_color: 0, 1, 0, 1
size_hint: 0.25, 0.20
on_release: app.show_data()
MDIconButton:
id: button
icon: "language-python"
pos_hint: {"center_x": .5, "center_y": .5}
on_release: app.dropdown1.open()
"""
class DemoApp(MDApp):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.screen = Builder.load_string(KV)
menu_items = [
{
"viewclass": "OneLineListItem",
"text": "Option1",
"on_release": lambda *args: self.callback()
}
]
self.dropdown1 = MDDropdownMenu(items=menu_items, width_mult=4, caller=self.screen.ids.button)
def build(self):
return self.screen
def show_data(self):
input_fahrenheit = self.root.ids.fahrenheit.text
print(input_fahrenheit)
#staticmethod
def callback():
print("cookies")
DemoApp().run()

random screen display with kivy

i am trying to make an app, a game actually that will display random screens when the "NEXT" button is touched, so i made the screens and the labels to be displayed on each screen but i cant get it to display a random screen when the "NEXT" button is touched, it just follows a pattern, would anyone help me here? heres the code:
#: import FadeTransition kivy.uix.screenmanager.FadeTransition
#: import Image kivy.uix.image.Image
#: import SoundLoader kivy.core.audio.SoundLoader
ScreenManagement:
transition: FadeTransition()
MainScreen:
GameScreen:
GameScreen2:
GameScreen3:
GameScreen4:
<Button>:
font_size: 12
size_hint: 0.2, 0.1
<MainScreen>:
name: "main"
FloatLayout:
Button:
text: "START GAME"
color: 1,0,1,1
pos_hint: {"x": 0, "y":0}
on_release: app.root.current = "game"
Button:
text: "QUIT"
color: 1,0,0,1
pos_hint: {"x": .8, "y": 0}
on_release: quit()
Button:
text: "SOUND"
color: 0,1,0,1
pos_hint: {"x":.2 , "y": .4}
on_press: app.play_sound1()
<GameScreen>:
name: "game"
FloatLayout:
Label:
text: "Python\nSnowden\nMr.Robot"
font_size: 40
color: 0,1,0,1
pos_hint: {"x":0, "y": 0}
Button:
text: "Home"
on_release: app.root.current = "main"
color: 1,0,0,1
pos_hint: {"right":1, "top":1}
Button:
text: "Next"
on_release: app.root.current = "game2"
color: 0,1,0,1
pos_hint: {"x":0, "y":0}
<GameScreen2>:
name: "game2"
FloatLayout:
Label:
text: "Banana\n\nOrange\n\nTea\n\nSleep"
font_size: 40
color: 0,1,0,1
pos_hint: {"x":0, "y": 0}
Button:
text: "Home"
on_release: app.root.current = "main"
color: 1,0,0,1
pos_hint: {"right":1, "top":1}
Button:
text: "Next"
on_release: app.root.current = "game3"
color: 0,1,0,1
pos_hint: {"x": 0, "y": 0}
<GameScreen3>:
name: "game3"
FloatLayout:
Label:
text: "Assembly\n\nRuby\n\nC"
font_size: 40
color: 0,1,0,1
pos_hint: {"x":0, "y":0}
Button:
text: "Home"
on_release: app.root.current = "main"
color: 1,0,0,1
pos_hint: {"right":1, "top":1}
Button:
text: "Next"
on_release: app.root.current = "game4"
color: 0,1,0,1
pos_hint: {"x": 0, "y": 0}
<GameScreen4>:
name: "game4"
FloatLayout:
Label:
text: "Prolog\n\nPygame\n\nC++"
font_size: 40
color: 0,1,0,1
pos_hint: {"x":0, "y":0}
Button:
text: "Home"
on_release: app.root.current = "main"
color: 1,0,0,1
pos_hint: {"right":1, "top":1}
the above is the kv code, sorry for the mess im an amateur when it comes to kivy
and heres the python side code:
from kivy.app import App
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.core.audio import SoundLoader
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
class MainScreen(Screen):
pass
class GameScreen(Screen):
pass
class GameScreen2(Screen):
pass
class GameScreen3(Screen):
pass
class GameScreen4(Screen):
pass
class ScreenManagement(ScreenManager):
pass
presentation = Builder.load_file("quora.kv")
class MainApp(App):
def build(self):
self.load_sounds()
return presentation
def load_sounds(self):
self.sounds = {}
for i in range(10):
fname = 'sound' + str(i+1) + '.wav'
self.sounds[i] = SoundLoader.load(fname)
def play_sound1(self):
sound = self.sounds.get(0)
if sound is not None:
sound.volume = 0.5
sound.play()
def play_sound2(self):
sound = self.sounds.get(1)
if sound is not None:
sound.volume = 0.5
sound.play()
if __name__ == "__main__":
MainApp().run()
this is the sample i made for you because the original one is way bigger than this i dont know how to use somewhat of a LOOP to generate screen so i made more that 20 screens on the original code so, and if you could help me figure out how can i STOP THE MENU SONG when i hit the "START" BUTTON, so that i can hit the "SONG" BUTTON on SCREEN1 to PLAY its SONG i would be gratefull. thanks you for the patience.
Display random screens when the "NEXT" button is touched
Use screen_names
screen_names
List of the names of all the Screen widgets added. The list is
read only.
screens_names is an AliasProperty and is read-only. It is updated
if the screen list changes or the name of a screen changes.
Snippets
#:import choice random.choice
...
Button:
text: "Next"
on_release:
root.manager.current = choice(root.manager.screen_names[1:])
color: 0,1,0,1
pos_hint: {"x":0, "y":0}
Stop / Play Music
You might want to use a ToggleButton instead of Button for playing music. Please refer to the example below.
Example
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.togglebutton import ToggleButton
from kivy.core.audio import SoundLoader
from kivy.properties import ObjectProperty
class MusicScreen(Screen):
enter = ObjectProperty(None)
text_input = ObjectProperty(None)
stop = ObjectProperty(None)
musicbutton = ToggleButton()
class ScreenManagement(ScreenManager):
pass
class MainApp(App):
sound = ObjectProperty(None, allownone=True)
def build(self):
return ScreenManagement()
def on_state(self, state, filename):
print("ONSTATE!!!")
print("\tstate=", state)
if self.sound is None:
self.sound = SoundLoader.load(filename)
# stop the sound if it's currently playing
if self.sound.status != 'stop':
self.sound.stop()
if state == "down":
self.sound.volume = .5
self.sound.play()
else: # if state == "normal":
if self.sound:
self.sound.stop()
# self.sound.unload()
self.sound = None
if __name__ == "__main__":
MainApp().run()
main.kv
#:kivy 1.11.0
<ScreenManagement>:
MusicScreen:
name: 'music'
<MusicScreen>:
text_input: text_input
id: "music"
name: "music"
BoxLayout:
size: root.size
pos: root.pos
orientation: "vertical"
FileChooserListView:
id: filechooser
rootpath: "/home/iam/Music/"
on_selection: text_input.text = self.selection and self.selection[0] or ''
TextInput:
id: text_input
size_hint_y: None
height: 50
multiline: False
ToggleButton:
size_hint: 1, .2
text: "Play/Stop By File"
on_state: app.on_state(self.state, text_input.text)
ToggleButton:
id: musicbutton
size_hint: 1, .2
text: "Play/Stop By Title"
on_state: app.on_state(self.state, text_input.text)

how to bind two or more events with on_text_validate

I want that on pressing enter in a TextInput widget it should do two things-
change the screen (i am using screen manager)
and search for the keyword
I do know that with on_text_validate we can perform either of the tasks by-
1.root.manager.current='namesomething'
2.root.function_which_has_search_algorithm()
is there anyway with which i can do both the things(changing_the_screen,calling_the_search_function) using on_text_validate or do i have to use some other technique?
here a sample code:
import kivy
kivy.require("1.10.0")
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager,Screen
from kivy.lang import Builder
Builder.load_file('screenswitch.kv')
class MainScreen(Screen):
def SelectWord(self):
''' some search
code'''
class OtherScreen(Screen):
pass
sm = ScreenManager()
sm.add_widget(MainScreen(name='main'))
sm.add_widget(OtherScreen(name='other'))
class ScreenSwitchApp(App):
def build(self):
return sm
obj = ScreenSwitchApp()
obj.run()
heres my kivy code:
<MainScreen>:
BoxLayout:
TextInput:
text: "Search your word here"
color: 1,1,1,1
id: search_input
width: 200
size_hint: None, .20
pos_hint: {"center_x": .5, "center_y": 0.5}
multiline: False
on_text_validate: root.SelectWord() # i want this to change screen also
<OtherScreen>:
BoxLayout:
Button:
text: 'back to main screen'
on_press: root.manager.current='main'
A possible solution is to create a new function that calls that 2 functions:
*.py
import kivy
kivy.require("1.10.0")
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager,Screen
from kivy.lang import Builder
Builder.load_file('screenswitch.kv')
class MainScreen(Screen):
def some_function(self):
self.SelectWord()
self.manager.current='other'
def SelectWord(self):
print("SelectWord")
class OtherScreen(Screen):
pass
sm = ScreenManager()
sm.add_widget(MainScreen(name='main'))
sm.add_widget(OtherScreen(name='other'))
class ScreenSwitchApp(App):
def build(self):
return sm
obj = ScreenSwitchApp()
obj.run()
*.kv
<MainScreen>:
BoxLayout:
TextInput:
text: "Search your word here"
color: 1,1,1,1
id: search_input
width: 200
size_hint: None, .20
pos_hint: {"center_x": .5, "center_y": 0.5}
multiline: False
on_text_validate: root.some_function() # i want this to change screen also
<OtherScreen>:
BoxLayout:
Button:
text: 'back to main screen'
on_press: root.manager.current='main'
TextInput:
id:qty_inp
size_hint_x:.1
multiline:False
on_text_validate:root.update_price()
on_text_validate:root.update_purchase
Like the above code you can add one more on_text_validate: root.method()

Categories

Resources