Kivy select screen in .py-file and use in .kv-file - python

I'm trying to make a list of screens and randomly select one of them in this python file (other code is not included here, like builder etc):
class selectionScreen
testScreen = StringProperty('Screen1')
def screenSelector(self)
screenList = ['Screen1', 'Screen2']
testNumber = random.randint(0, 1)
testScreen = screenList[testNumber]
return testscreen
I then want to choose this screen in my .kv-file, which looks somewhat like this, but also includes screen 1 and 2
ScreenManager:
SelectionScreen:
name: 'SelectionScreen'
Screen0:
name: 'Screen0'
Screen1:
name: 'Screen1'
<SelectionScreen>:
BoxLayout:
Button:
text: "Click when ready"
size_hint: .6, .5
font_size: 10
on_press: root.screenSelector()
on_release: root.manager.current = 'Screen0'
<Screen0>:
BoxLayout:
orientation: 'vertical'
Button:
text: "Next"
on_release: root.manager.current = str(root.testScreen)
The SelectionScreen is working fine, but now I am not able to reach screen0. When removing the line
on_press: root.screenSelector()
I can, however, do this.
Thank you in advance for any help!

Problem
You are not able to reach screen0 because it is not in your screenList.
The variable, testScreen defined in method screenSelector is a local variable, which is not the same class variable, testScreen defined in class selectionScreen.
Undefined variable, return testscreen due to typo error.
At Screen0, the code, on_release: root.manager.current = str(root.testScreen) will cause an AttributeError: 'Screen0' object has no attribute 'testScreen'
Solution
In order to reach Screen0, you have to do the following:
Python Script
Add Screen0 into the variable, screenList
Replace random.randint(0, 1) with random.randint(0, 2)
Replace testScreen with self.testScreen in method screenSelector
kv file
Define an id, e.g. id: selection_screen
Reference it, e.g. root.manager.ids.selection_screen.testScreen
Add on_press call to screenSelector in the other screens, e.g. on_press: root.manager.ids.selection_screen.screenSelector()
Example
main.py
from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.properties import StringProperty
import random
class ScreenManager(ScreenManager):
pass
class SelectionScreen(Screen):
testScreen = StringProperty('Screen1')
def screenSelector(self):
screenList = ['Screen0', 'Screen1', 'Screen2']
testNumber = random.randint(0, 2)
self.testScreen = screenList[testNumber]
return self.testScreen
class Screen0(Screen):
pass
class Screen1(Screen):
pass
class Screen2(Screen):
pass
class Test(App):
def build(self):
return ScreenManager()
if __name__ == "__main__":
Test().run()
test.kv
#:kivy 1.10.0
<ScreenManager>:
SelectionScreen:
id: selection_screen
name: 'SelectionScreen'
Screen0:
name: 'Screen0'
Screen1:
name: 'Screen1'
Screen2:
name: 'Screen2'
<SelectionScreen>:
BoxLayout:
Button:
text: "Click when ready"
size_hint: .6, .5
font_size: 10
on_press: root.screenSelector()
on_release:
root.manager.current = str(root.manager.ids.selection_screen.testScreen)
<Screen0>:
BoxLayout:
orientation: 'vertical'
Button:
text: "Screen 0"
on_press: root.manager.ids.selection_screen.screenSelector()
on_release:
root.manager.current = str(root.manager.ids.selection_screen.testScreen)
<Screen1>:
BoxLayout:
orientation: 'vertical'
Button:
text: "Screen 1"
on_press: root.manager.ids.selection_screen.screenSelector()
on_release:
root.manager.current = str(root.manager.ids.selection_screen.testScreen)
<Screen2>:
BoxLayout:
orientation: 'vertical'
Button:
text: "Screen 2"
on_press: root.manager.ids.selection_screen.screenSelector()
on_release:
root.manager.current = str(root.manager.ids.selection_screen.testScreen)
Output

Related

Python Kivy Dyanmic Class not defined

I keep getting a Name Error reporting "name TripButton is not defined" although I have a button called TripButton defined in the same .kv file.
#:kivy 1.11.1
<TripButton#Button>:
size_hint: (0.15,0.15)
pos_hint: {'y':0.84}
text:"Test Text"
<MyPopup>:
size_hint: 0.5, 0.5
auto_dismiss: False
title: 'New Trip'
BoxLayout:
orientation: 'vertical'
TextInput:
id: trip_name
multiline: False
BoxLayout:
size_hint_y: None
height: 30
Button:
text: 'Submit'
on_release:
root.parent.parent.add_widget(TripButton(text=trip_name.text, size_hint=(1,0.1)))
root.dismiss()
Button:
text: 'Cancel'
on_release: root.dismiss()
<FirstScreen>:
name: 'first'
FloatLayout:
BoxLayout:
size_hint: (0.95, 0.95)
pos_hint: {'center_x':0.5, 'center_y':0.5}
orientation: "vertical"
canvas.before:
Color:
rgba: (1, 0, 0, 1) # Red color
Rectangle:
pos: self.pos
size: self.size
BoxLayout:
TripButton:
Button:
text: 'Add Trip'
font_size: 12
size_hint: (0.1, 0.1)
pos_hint: {'right':1, 'bottom':1}
on_release: app.open_popup()
pos_hint: {'right':1, 'bottom':1}
on_release: app.open_popup()
I tried declaring the TripButton class above and below the MyPopup class and that didn't work. I compared my code with the kivy documentation for dynamic classes and the from what I can tell I'm matching the syntax. I tried importing the Button class in both the python file and the .kv file and that hasn't worked.
To clarify all of this is in the same .kv file in the same directory as the python file. the app runs until I click the submit button in MyPopup then the program crashes and I get the NameError. This is what I have in my python file.
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.popup import Popup
class FirstScreen(Screen):
pass
class MyPopup(Popup):
pass
class MyApp(App):
def build(self):
sm = ScreenManager()
sm.add_widget(FirstScreen(name='first'))
sm.current = 'first'
return sm
def open_popup(self):
p = MyPopup()
p.open()
def add_button(self):
pass
if __name__ == '__main__':
MyApp().run()
What am I doing wrong? What else I can try? Thanks for your time.
To access classes defined within kv file use kivy.factory.Factory
Add id attribute to your button's BoxLayout, so replace following part of kv file:
BoxLayout:
TripButton:
with
BoxLayout:
id: trip_buttons
TripButton:
then replace:
root.parent.parent.add_widget(TripButton(text=trip_name.text, size_hint=(1,0.1)))
with:
app.root.current_screen.ids.trip_buttons.add_widget(kivy.factory.Factory.TripButton(text=trip_name.text, size_hint=(1,0.1)))
You also duplicated following lines within last button definition on first screen. Replace:
pos_hint: {'right':1, 'bottom':1}
on_release: app.open_popup()
pos_hint: {'right':1, 'bottom':1}
on_release: app.open_popup()
with
pos_hint: {'right':1, 'bottom':1}
on_release: app.open_popup()

How can I change the text of a button in another screen when I am in a popup-window?

I am trying to change the label of the button "Choose Activity" to "Schlafen" (in the Screen "DayWindow"), if the user clicks on the button "Schlafen" in the popup window.
My problem is that I dont know how to access the Screen "DayWindow" from the Popup-Class.
As you can see in the code, I tried to access it through the ScreenManager but than I get the Error: 'super' object has no attribute '__getattr__'
In another try I got the Error: Screen "day" does not exist
I would be very thankful for any help and tips.
My Pyhton File:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.app import runTouchApp
from kivy.properties import ObjectProperty
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.popup import Popup
from kivy.properties import ObjectProperty
from datetime import date, timedelta
import json
class MenuWindow(Screen):
pass
class DayWindow(Screen):
null = ObjectProperty("Null")
def btn(self,index):
show_ActivityPopup()
def change_button():
scn = ScreenManager()
scn.ids.null.text = "Geschafft"
class WeekWindow(Screen):
pass
class MonthWindow(Screen):
pass
class WindowManager(ScreenManager):
pass
class ActivityPopup(FloatLayout):
def change_text(self):
DayWindow.change_button()
def show_ActivityPopup():
show = ActivityPopup()
ActivityPopupWindow = Popup(title="Activities", content=show, auto_dismiss=False)
ActivityPopupWindow.open()
kv = Builder.load_file("my.kv")
class MyMainApp(App):
def build(self):
return kv
if __name__ == "__main__":
MyMainApp().run()enter code here
My .kv - File
WindowManager:
MenuWindow:
DayWindow:
WeekWindow:
MonthWindow:
<MenuWindow>:
name: "menu"
GridLayout:
cols:1
Label:
text: "Time/MoodTracker"
Button:
text: "Day"
on_release:
app.root.current = "day"
root.manager.transition.direction ="left"
GridLayout:
cols: 2
Button:
text: "Weelky Overview"
on_release:
app.root.current = "week"
root.manager.transition.direction ="left"
Button:
text: "Monthly Overview"
on_release:
app.root.current = "month"
root.manager.transition.direction ="left"
<DayWindow>:
name: "day"
ScrollView:
GridLayout:
cols: 2
Label:
text: "0:00 - 0:30"
Button:
id: null
text: root.null
on_release:
root.btn(0)
Label:
text: "0:30 - 1:00"
id: Eins
Button:
text: "Choose Aviticity"
on_release: root.btn(1)
Label:
text: "1:00 - 1:30"
Button:
text: "Choose Aviticity"
on_release: root.btn(2)
Label:
text: "1:30 - 2:00"
Button:
text: "Choose Aviticity"
on_release: root.btn(3)
Label:
text: "2:00 - 2:30"
Button:
text: "Choose Aviticity"
on_release: root.btn(4)
<ActivityPopup>:
auto_dismiss: False
ScrollView:
GridLayout:
size_hint_y: None
cols:1
height: dp(600)
spacing: "10dp"
Button:
text: "Schlafen"
on_release:
root.change_text()
root.parent.parent.parent.dismiss()
Button:
text: "Frühstücken"
on_release:
root.parent.parent.parent.dismiss()
Button:
text: "Kochen"
Button:
text: "Lernen"
Button:
text: "Joggen"
<WeekWindow>:
name: "week"
Button:
text: "Back"
on_release:
app.root.current = "menu"
root.manager.transition.direction ="right"
<MonthWindow>:
name: "month"
Button:
text: "Back"
on_release:
app.root.current = "menu"
root.manager.transition.direction ="right"
A couple problems:
The code:
def change_button():
scn = ScreenManager()
scn.ids.null.text = "Geschafft"
is creating a new instance of ScreenManager, which has nothing to do with your App. So nothing that you do with scn will have any effect on your App.
And, in that same method, you are trying to access ids of the ScreenManager. Even if you were actually dealing with the WindowManager in your App, this would not work, because the WindowsManager has no defined ids.
The ids defined in your kv file are defined in the object that is the root of the rule where that id is defined. So, for example, the null id is defined in the ids of the DayWindow. The kivy documentation on this issue is confusing due to its multiple uses of the term root widget.
The fix is to just modify the change_text() method of the ActivityPopup class. Here is an updated version of that method, that should fix your problems:
class ActivityPopup(FloatLayout):
def change_text(self):
scn = App.get_running_app().root.get_screen('day')
scn.ids.null.text = "Geschafft"

Recup input value through screen manager kivy

I want to catch a value from my first screen into my thirdscreen.
In the first, I write my name in an input field.
I go to the next window.
And I try to show my name in this last window.
So I share the code with you and I hope I will find an issue.
Python code :
import kivy
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.properties import ObjectProperty
from kivy.uix.screenmanager import ScreenManager, Screen
#define ou different screens
class FirstWindow(Screen):
def envoyer(self):
name = self.ids.nom_input.text
self.ids.my_name.text = name
class SecondWindow(Screen):
pass
class ThirdWindow(Screen):
#PROBLEM HERE
def on_press(self):
self.ids.recup_infos.text = self.root.get_screen('FirstWindow').ids.my_name.text
class WindowManager(ScreenManager):
pass
class MonWidget(Widget):
pass
kv = Builder.load_file('new_window.kv')
class AwesomeApp(App):
def build(self):
Window.clearcolor = (0,0,0,0)
return kv
if __name__ == '__main__':
AwesomeApp().run()
My KV CODE :
WindowManager:
FirstWindow:
SecondWindow:
ThirdWindow:
<FirstWindow>:
name: "romain"
BoxLayout:
orientation: "vertical"
size: root.width, root.height
Label:
id: my_name
text: "Entrez votre nom"
font_size: 32
TextInput:
id: nom_input
multiline: False
size_hint: (1, .5)
Button:
text: "Next screen"
font_size: 32
on_press: root.envoyer()
on_release:
app.root.current = "Mickael"
root.manager.transition.direction = "left"
<SecondWindow>:
name: "Mickael"
BoxLayout:
orientation: "vertical"
size: root.width, root.height
Label:
text: "Entre votre ville"
font_size: 32
TextInput:
id: ville_input
multiline: False
size_hint: (1, .5)
Button:
text: "Vérifier les infos"
font_size: 32
on_release:
app.root.current = "foncier"
root.manager.transition.direction = "left"
Button:
text: "go back first screen"
font_size: 32
on_release:
app.root.current = "romain"
root.manager.transition.direction = "right"
<ThirdWindow>:
name: "foncier"
BoxLayout:
orientation: "vertical"
size: root.width, root.height
Label:
text: "Verifier : "
font_size: 32
Label:
id: recup_infos
text: ""
font_size: 32
color: 'white'
Button:
text: "On press"
font_size: 32
#Problem HERE
on_press: root.on_press()
Button:
text: "Précedent"
font_size: 32
on_release:
app.root.current = "Mickael"
root.manager.transition.direction = "right"
Could you help me ?
Thank you
Romain
In your on_press method:
def on_press(self):
self.ids.recup_infos.text = self.root.get_screen('FirstWindow').ids.my_name.text
self.root.get_screen('FirstWindow').ids.my_name.text isn't the correct way to get access to widgets outside of the class that you are in right now, or in this situation, screen. The correct way is to use the App.get_running_app() method:
self.ids.recup_infos.text = App.get_running_app().root.ids.First.ids.my_name.text
But before doing that, you have to give ids to the screens of your app, so that the First argument of the method demonstrated above actually makes sense:
WindowManager:
FirstWindow:
id: First
# "First" is the id of the FirstWindow class
# which can also explain why there was a "First" arg
# inside "App.get_running_app().root.ids.First.ids.my_name.text"
SecondWindow:
id: Second
ThirdWindow:
id: Third
Still confused to why this works? Let's divide the attributes of App.get_running_app().root.ids.First.ids.my_name.text into 3 parts:
App.get_running_app(): this method returns the location of your running App class, in this case AwesomeApp. This also acts as self if you were to get the variable inside the App object itself
.root.ids.First: if you read the Kivy documentation, or just simply watched Kivy course videos online, carefully, you should know that self.root.ids inside the App object returns a list of ids of the widgets inside your root widget. In this case, App.get_running_app().root.ids is doing the same thing here, and your screens are passed in the ScreenManager root widget, hence make First an available attribute in App.get_running_app().root.ids
.ids.my_name.text: same as above, App.get_running_app().root.ids.First acts the same as self if you were to run it in your FirstWindow class, which gives you the opportunity to get access to variables outside of your working classes/screens

Passing a text input between screens in Kivy

I am having trouble taking a text input value from one screen and passing it as the text in a label in another screen. I want to take the text input from a TeamNameSelect screen and have those be the text values in the labels of a GameWindow screen. I've tried going through similar questions and answers on here but have been unable to get this to work. Any help would be greatly appreciated!
.py file
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.button import Button
from kivy.uix.widget import Widget
class NewGame(Screen):
pass
class GameWindow(Screen):
def teamNames(self, *args):
self.teamOne_input.text = self.manager.ids.TeamNameSelect.ids.teamOne.text
self.teamTwo_input.text = self.manager.ids.TeamNameSelect.ids.teamTwo.text
pass
class TeamNameSelect(Screen):
pass
class WinMan(ScreenManager):
pass
kv = Builder.load_file("my.kv")
sm = WinMan()
screens = [NewGame(name='goBack'), TeamNameSelect(name='teamSelect'), GameWindow(name='startGame')]
for screen in screens:
sm.add_widget(screen)
sm.current = 'goBack'
class MyApp(App):
def build(self):
return sm
if __name__ == '__main__':
MyApp().run()
.kv file
<TeamNameSelect>:
BoxLayout:
orientation: 'vertical'
BoxLayout:
orientation: 'vertical'
padding: 10
Label:
text: 'Team 1 Name: '
TextInput:
id: teamOne
text: ''
multiline: False
BoxLayout:
orientation: 'vertical'
padding: 10
Label:
text: 'Team 2 Name: '
TextInput:
id: teamTwo
text: ''
multiline: False
BoxLayout:
Button:
text: 'Go Back'
on_release: root.manager.current = 'goBack'
Button:
text: 'Game On!'
on_release:
root.manager.current = 'gameWindow'
root.teamNames()
<GameWindow>:
teamOne_input: teamOne_input
teamTwo_input: teamTwo_input
BoxLayout:
orientation: 'vertical'
BoxLayout:
orientation: 'horizontal'
size_hint: (1, 0.1)
Button:
text: '. . .'
on_release: root.manager.current = 'goBack'
Label:
font_size: 33
text: 'Team'
Label:
font_size: 33
id: teamOne_input
text: ''
Label:
font_size: 33
text: 'Team'
Label:
font_size: 33
id: teamTwo_input
text: ''
BoxLayout:
orientation: 'horizontal'
size_hint: (0.75,1)
Label:
font_size: 33
text: '' # Instructions on how to play game
Label:
font_size: 39
text: '' # Future playing area to develop
You have 2 preliminary errors:
There is no Screen with name "gameWindow" so I suppose the OP wanted to write "startGame".
The root in on_release is the "TeamNameSelect" that clearly has nothing that does not have the teamNames() method.
On the other hand the "manager" is not implemented in the .kv so it cannot have any "id", the solution is to access the screen with name "teamSelect" using the get_screen() method.
Considering the above, the solution is:
class GameWindow(Screen):
def teamNames(self):
select_screen = self.manager.get_screen("teamSelect")
self.teamOne_input.text = select_screen.ids.teamOne.text
self.teamTwo_input.text = select_screen.ids.teamTwo.text
Button:
text: 'Game On!'
on_release:
root.manager.current = 'startGame'
root.manager.current_screen.teamNames()

Kivy with Menubar

I want to create a Kivy-App with a Menubar which is always the same.
My Code:
demo.py:
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.boxlayout import BoxLayout
class Display(BoxLayout):
pass
class Screen_One(Screen):
pass
class Screen_Two(Screen):
pass
class DemoApp(App):
def build(self):
return Display()
if __name__ == '__main__':
DemoApp().run()
demo.kv:
<Display>:
BoxLayout:
orientation: "vertical"
BoxLayout:
size_hint: 1, None
height: '48dp'
Button:
text: 'One'
on_release: sm.current = 'Screen_One'
Button:
text: 'Two'
on_release: sm.current = 'Screen_Two'
ScreenManager:
id: sm
Screen_One:
Screen_Two:
<Screen_One>:
Button:
text: 'One'
<Screen_Two>:
Button:
text: 'Two'
But it doesn't work, if i click on "One" i received:
kivy.uix.screenmanager.ScreenManagerException: No Screen with name "Screen_One".
I reduced my code to the leading part. I also tried to put the menu-kivy-code in a seperate file and import but then i also can't access the ScreenManager and can't switch the Screens.
ScreenManager.current atribute is the name of the screen currently shown. You have not set the name attribute in your classes (screens). Your demo.kv file should be:
<Display>:
BoxLayout:
orientation: "vertical"
BoxLayout:
size_hint: 1, None
height: '48dp'
Button:
text: 'One'
on_release: sm.current = 'screen_one' #<<<<<<<<<<<<<<<<
Button:
text: 'Two'
on_release: sm.current = 'screen_two' #<<<<<<<<<<<<<<<<
ScreenManager:
id: sm
Screen_One:
Screen_Two:
<Screen_One>:
name: 'screen_one' #<<<<<<<<<<<<<<<<
Button:
text: 'One'
<Screen_Two>:
name: 'screen_two' #<<<<<<<<<<<<<<<<
Button:
text: 'Two'

Categories