I have an App with three toggle buttons in a fixed header that is an outside indented layout for screen manager. On initialisation, the Import screen must show i.e. self.ids.scrn_man.current = 'import_scn" and when a toggle button is pushed a next screen should show i.e. on_state: scrn_man.current = "settings_scrn".
But for some reason, only the header is showing and the screens do not want to transition. I don't get any errors.
I tried different layouts as my Apps main class inheritance including, FloatLayout, StackLayout and BoxLayout. I also made the header fixed with AnchorLayout and use a different layout as the inline layout for ScreenManager. If I remove the ScreenManager I see my widgets, but of course, I cannot transition. I did at first try using TabbedPanel to house my different widgets but I encountered a constant RefError: weak object reference if I added too many widgets (but that's not for now). So I re-designed with something I knew worked on a previous App albeit less complex.
Here is my faulty code:
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.stacklayout import StackLayout
from kivy.uix.togglebutton import ToggleButton
from kivy.lang import Builder
from kivy.uix.popup import Popup
from kivy.properties import StringProperty, ObjectProperty
Builder.load_string("""
<RoundedButton#Button>:
background_color: 0,0,0,0
canvas.before:
Color:
rgba: (.47,.47,.47,1) if self.state=='normal' else (1,.6,0,1)
RoundedRectangle:
pos: self.pos
size: self.size
radius: [8,]
<RoundedCancelButton#Button>:
background_color: 0,0,0,0
canvas.before:
Color:
rgba: (.47,.47,.47,1) if self.state=='normal' else (1,.2,.2,1)
RoundedRectangle:
pos: self.pos
size: self.size
radius: [8,]
<RoundedAcceptButton#Button>:
background_color: 0,0,0,0
canvas.before:
Color:
rgba: (.47,.47,.47,1) if self.state=='normal' else (.2,1,.6,1)
RoundedRectangle:
pos: self.pos
size: self.size
radius: [8,]
<TabbedContainer#ToggleButton>:
background_color: (1, .5, 0, 1)
background_normal: ''
size_hint_y: None
height: 50
size_hint_x: (1 / 3)
spacing: 30
<Tab>:
canvas.before:
Color:
rgba: (.89, .89, .89, 1)
Rectangle:
size: self.size
pos: self.pos
orientation: 'lr-tb'
BoxLayout:
orientation: 'horizontal'
size_hint_y: None
height: 30
canvas.before:
Color:
rgba: (1, .3, 0, 1)
Rectangle:
size: self.size
pos: self.pos
Label:
text: 'Test'
color: (1, 1, 1, 1)
size_hint_x: 1
StackLayout:
orientation: 'lr-tb'
Label:
text: ''
size_hint_x: 1
size_hint_y: None
height: 10
TabbedContainer:
id: import_tog
text: 'Import'
state: 'down'
group: 'admin_navs'
on_state: root.change_screen(self)
TabbedContainer:
id: calculate_tog
text: 'Calculate'
group: 'admin_navs'
on_state: root.change_screen(self)
TabbedContainer:
id: settings_tog
text: 'Settings'
group: 'admin_navs'
on_state: root.change_screen(self)
BoxLayout:
id: ui_content
padding: 10
ScreenManager: #Problem here I think
id: scrn_man
Screen:
id: import_scrn
name: 'import_scrn'
StackLayout:
orientation: 'lr-tb'
Label:
text: ''
size_hint_x: 1
Label:
text: ''
size_hint_x: 0.2
RoundedButton:
text: 'Choose File'
size_hint_x: 0.2
TextInput:
id: get_file
readonly: True
size_hint_x: 0.5
Label:
text: ''
size_hint_x: 0.1
Label:
text: ''
size_hint_x: 0.2
RoundedButton:
text: 'Import'
size_hint_x: 0.2
Label:
text: ''
size_hint_x: 0.6
StackLayout:
id: import_data_content
orientation: 'lr-tb'
size_hint_y: None
height: 90
Screen:
id: calculate_scrn
name: 'calculate_scrn'
Screen:
id: settings_scrn
name: 'settings_scrn'
StackLayout:
orientation: 'lr-tb'
size_hint_x: 0.5
Label:
text: ''
size_hint_x: 0.1
Button:
text: 'Add Employee'
size_hint_x: 0.2
Label:
text: ''
size_hint_x: 0.2
Button:
text: 'CSV'
size_hint_x: 0.2
Label:
text: ''
size_hint_x: 0.3
BoxLayout:
orientation: 'horizontal'
size_hint_x: 0.5
Label:
text: 'In Time'
size_hint_x: 0.7
TextInput:
size_hint_x: 0.3
Label:
text: 'Out Time'
size_hint_x: 0.7
TextInput:
size_hint_x: 0.3
""")
class TabbedContainer(ToggleButton):
pass
class FileChoosePopup(Popup):
load = ObjectProperty()
class RoundedButton(Button):
pass
class RoundedCancelButton(Button):
pass
class RoundedAcceptButton(Button):
pass
class Tab(StackLayout):
file_path = StringProperty("No file chosen")
the_popup = ObjectProperty(None)
def __init__(self, **kwargs):
super().__init__(**kwargs)
#load import window on initialisation
import_window = self.ids.import_scrn
self.ids.scrn_man.current = 'import_scrn'
def change_screen(self, instance):
if instance.text == 'Import':
self.ids.scrn_man.current = 'import_scrn'
elif instance.text == 'Calculate':
self.ids.scrn_man.current = 'calculate_scrn'
else:
self.ids.scrn_man.current = 'settings_scrn'
class TestApp(App):
def build(self):
return Tab()
if __name__ == '__main__':
TestApp().run()
I expect that the import screen must show on initialisation and screens transition on toggle button state: down. Can someone please give me some advice on how to make my App act as explained above?
Your screens are loading correctly according to your settings. You need to review your entire kv string looking at your size_hint settings. Check each item that contains children and make sure that the total of size_hint_x for its children is less than or equal to 1.0 and the same for size_hint_y.
Related
I am trying to code a simple quiz game. There're supposed to be multiple screens, the first screen (LoginWindow) being a simple login form. After the login and confirmation of the right name and password being entered the second screen (GameWindow) is supposed to show up, but it doesn't. Right from the start the second screen is being loaded.
I'm sure I am missing something super simple and basic but I just don't get it.
.py file:
from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.screenmanager import ScreenManager, Screen
import hashlib
Window.size = (512, 512)
user_hash = ""
pass_hash = ""
super_user = "9279F4A7C1C145D5AE930FDA23EF386168F6720B4E0F0D3DEE383C5AD8535737"
super_pass = "EE22032527082315A747781829EF1F9195F6AEAC09C0D52DE06EBF9D8C463918"
# Define screens
class LoginWindow(Screen):
name = ObjectProperty(None)
passw = ObjectProperty(None)
def press(self):
user_hash = hashlib.sha256(self.name.text.encode('utf-8')).hexdigest().upper()
pass_hash = hashlib.sha256(self.passw.text.encode('utf-8')).hexdigest().upper()
if (user_hash == super_user) and (pass_hash == super_pass):
print("Das hat geklappt!")
WindowManager.current = 'game'
else:
print("Du kummst hier net rein!")
class GameWindow(Screen):
pass
class WindowManager(ScreenManager):
pass
kv = Builder.load_file('box_multiscreen.kv')
class Affenquiz(App):
def build(self):
Window.clearcolor = (0.8, 0.8, 0.8, 1)
WindowManager = ScreenManager()
WindowManager.add_widget(LoginWindow(name='login'))
WindowManager.add_widget(GameWindow(name='game'))
WindowManager.current = 'login'
return kv
if __name__ == "__main__":
Affenquiz().run()
.kv file:
WindowManager:
LoginWindow:
name: "login"
GameWindow:
name: "game"
<LoginWindow>:
name:name
passw:passw
BoxLayout:
orientation: "vertical"
size: root.width, root.height
spacing: 20
padding: 20
canvas.before:
Rectangle:
pos: self.pos
size: self.size
source: 'monkey.png'
AnchorLayout:
anchor_y: 'top'
BoxLayout:
orientation: "horizontal"
size_hint: (1, None)
height: 50
Label:
text: "Der Quizfelsen"
font_size: 50
BoxLayout:
orientation: "horizontal"
size_hint: (1, None)
height: 50
Label:
text: "Benutzer:"
TextInput:
id: name
multiline:False
background_color: (241/255.0,241/255.0,241/255.0,0.9)
BoxLayout:
orientation: "horizontal"
size_hint: (1, None)
height: 50
Label:
text: "Passwort:"
TextInput:
id: passw
multiline:False
background_color: (241/255.0,241/255.0,241/255.0,0.9)
RoundedButton:
text: "Login"
pos_hint: {'center_x': .5}
size_hint: (1, None)
height: 50
on_press: root.press()
<GameWindow>:
Label:
text: "Der Quizfelsen"
font_size: 50
<Label>
font_size: 32
background_normal: ''
background_color: (0.9,0.9,0.9,0)
canvas.before:
Color:
rgba: self.background_color
Rectangle:
size: self.size
pos: self.pos
color: (184/255.0,70/255.0,35/255.0,1)
bold: True
outline_color: (1,1,1,1)
outline_width: 2
<RoundedButton#Button>
background_color: (0,0,0,0)
background_normal: ''
canvas.before:
Color:
rgba: (184/255.0,70/255.0,35/255.0,0.9)
RoundedRectangle:
size: self.size
pos: self.pos
radius: [25]
Thank you in advance
This is how my program looks right now.
How can I position my button "Log in" to always be horizontally aligned with center? I've tried looking on Stack Overflow about similar stuff but nothing worked for me... If anyone can help me, I would be really thankful.
Here's my python code:
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.core.window import Window
from kivy.uix.gridlayout import GridLayout
import kivy.properties as kyprops
from kivy.uix.widget import Widget
from kivy.uix.image import Image
Builder.load_file("main.kv")
Window.clearcolor = (1,1,1,1)
# Declare both screens
class LoginScreen(Screen):
#txt_inpt = kyprops.ObjectProperty(None)
#def __init__(self):
pass
class InfoScreen(Screen):
pass
# Create the screen manager
sm = ScreenManager()
sm.add_widget(LoginScreen(name='Login'))
sm.add_widget(InfoScreen(name='Info'))
class TestApp(App):
def build(self):
return sm
if __name__ == '__main__':
TestApp().run()
Here is my .kv code:
#:import C kivy.utils.get_color_from_hex
<LoginScreen>:
RelativeLayout:
txt_inpt: txt_inpt
canvas:
Color:
rgba: C('#336699')
Line:
width: 2
rectangle: (0,self.height-50,self.width,0)
id: linija
Ellipse:
pos: self.width- 35, self.height-15
size: 7 , 7.0000000001
angle_start: 0
angle_end: 360
Ellipse:
pos: self.width- 35, self.height-27
size: 7 , 7.0000000001
angle_start: 0
angle_end: 360
Ellipse:
pos: self.width- 35, self.height-39
size: 7 , 7.0000000001
angle_start: 0
angle_end: 360
TextInput:
id: txt_inpt
password: True
multiline: False
hint_text: 'Username'
hint_text_color: C('#b3ccff')
size_hint_x: 0.9
size_hint_y: None
pos_hint: {"x":0.05, "top":0.8}
background_color: (1,1,1,0.2)
on_text_validate: root.manager.current = 'Info'
height: 30
pos: 300,60
TextInput:
id: txt_inpt
password: True
multiline: False
hint_text: 'Password'
hint_text_color: C('#b3ccff')
size_hint_x: 0.9
size_hint_y: None
pos_hint: {"x":0.05, "top":0.7}
background_color: (1,1,1,0.2)
on_text_validate: root.manager.current = 'Info'
height: 30
pos: 300,60
BoxLayout:
width: 1
pos: self.parent.pos # important!
orientation: 'vertical'
halign: 'center'
Button:
on_press: root.manager.current = 'Info'
background_color: C('#336699')
pos: self.pos
size: self.size
size: 80,30
size_hint: None, None
## NOTE: pos_hint: {"x":0.45, "top":0.6}
font_name: 'Droid.otf'
text: 'Log in'
<InfoScreen>:
BoxLayout:
Button:
text: 'My settings button'
Button:
text: 'Back to menu'
on_press: root.manager.current = 'Login'
Your line in kv:
pos: self.parent.pos # important!
is positioning the BoxLayout in the lower left corner of the RelativeLayout
You can center it by using pos_hint and minimum_width:
BoxLayout:
# width: 1
# pos: self.parent.pos # important!
pos_hint: {'center_x':0.5, 'y':0}
size_hint_x: None
width: self.minimum_width
orientation: 'vertical'
I'm pretty new to python and kivy and I'm trying to build my first app for my masterthesis. The problem I'm struggeling with right now is that I have multiple python and kivy files, and my app includes a group of Toggle buttons and Spinners. I want to 'store'/assign theselected values and print them when i hit my submit button. I'm working with multiple python and kivy files. The app also has some sliders and i managed to get those values when pressing submit, but can't figure it out for toggles nor spinners. I hope you can help!:)
Main .py, rather important:
import kivy
from kivy.app import App
from kivy.uix.button import Label
from kivy.uix.widget import Widget
from kivy.uix.textinput import TextInput
from kivy.lang import Builder
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BooleanProperty
from kivy.properties import ObjectProperty
Builder.load_file('Header.kv')
Builder.load_file('Statusbar.kv')
Builder.load_file('Inputparameters.kv')
Builder.load_file('Outputparameters.kv')
#Layout
class Peenomat(AnchorLayout):
def show_selected_value(self, spinner, text):
print(spinner, text)
#pass
#DropDown in Inputparameters
#class InputParameters(BoxLayout):
#state = BooleanProperty(False)
class PeenomatApp(App):
def build(self):
return Peenomat()
if __name__=="__main__":
PeenomatApp().run()
The main kv file:
AnchorLayout:
anchor_x: 'left'
anchor_y: 'bottom'
GridLayout:
cols: 1
canvas.before:
Color:
rgba: 0.75 ,0.75, 0.75, 1
Rectangle:
pos: self.pos
size: self.size
Header:
id: _header
size_hint: 1, 0.1
#height: 100
InputParameters:
id:_input_parameters
size_hint: 1, 0.45
StatusBar:
id:_status_bar
size_hint: 1, 0.1
#height: 50
OutputParameters:
id:_output_parameters
size_hint: 1, 0.35
The .kv file that includes the toogle buttons, spinners, and sliders where i guess most of the implemantation needs to be done
#: import statusbar StatusBar
<InputParameters#GridLayout>
prozess: _proz_value
prozess1: _prozess1
prozess2: _prozess2
prozess3: _prozess3
vorbehandlung: _vorbehandlung
material: _material
haerte: _haerte
rauheit: _rauheit
cols: 2
padding: 15
spacing: 15
#Farbe Schrift Label
cb: (1,1, 1,1)
#Farbe Slider
cs: (0,0.353, 0.663,1)
#FontSize
fs: 20
#Prozess
Label:
text:'Prozess: '
bold: True
font_size: root.fs
text_size: self.size
halign: 'left'
valign: 'center'
color: root.cb
BoxLayout:
orientation: 'horizontal'
id: _proz_value
_proz_value: 0
ToggleButton:
text:'P-MOH'
id: _prozess1
group: "proc_group"
background_color: 0.0, 0.353, 0.663, 1.0
bold: True
on_press: root._proz_value = 1
ToggleButton:
text:'E-MOH'
id: _prozess2
group: "proc_group"
background_color: 0.0, 0.353, 0.663, 1.0
bold: True
on_press: root._proz_value = 2
ToggleButton:
text:'PE-MOH'
id: _prozess3
group: "proc_group"
background_color: 0.0, 0.353, 0.663, 1.0
bold: True
on_press: root._proz_value = 3
#Material
Label:
text: 'Material: '
bold: True
font_size: root.fs
text_size: self.size
halign: 'left'
valign: 'center'
color: root.cb
Spinner:
id: _material
# Callback
on_text:
text: "Auswahl treffen"
bold:True
values: ['1.2379', 'Gusseisen', 'Kautschuk', 'Carbon', 'Adamantium']
#background_normal: '[1,1,1,1]'
background_color: root.cs
color: root.cb
# Herstellschritte
Label:
text:'Fertigungsschritte: '
bold: 'True'
font_size: root.fs
text_size: self.size
halign: 'left'
valign: 'center'
color: root.cb
Spinner:
id: _vorbehandlung
# Callback
on_text:
app.root.show_selected_value(self, self.text)
text: "Auswahl treffen"
bold:True
values: ['Fräsen', 'Erodieren', 'Schleifen', 'Polieren']
#background_normal: '[1,1,1,1]'
background_color: root.cs
color: root.cb
# Haerte
Label:
text:'Haerte: '
bold: True
font_size: root.fs
text_size: self.size
halign: 'left'
valign: 'center'
color: root.cb
BoxLayout:
orientation: 'vertical'
spacing: 15
Label:
text: str(_haerte.value) + ' HRC'
color: root.cs
bold: True
Slider:
id: _haerte
min: 45
max: 65
value:55
step: 1
value_track: True
value_track_color: root.cs
# Rauheit
Label:
text:'Rauheit: '
#color: cb
bold: True
font_size: root.fs
text_size: self.size
halign: 'left'
valign: 'center'
color: root.cb
BoxLayout:
orientation: 'vertical'
spacing: 15
Label:
text: str("%.1f" % _rauheit.value) + ' Rz' #eine Nachkommastelle
color: root.cs
bold: True
Slider:
id: _rauheit
min: 1
max: 10
value:5.5
step: 0.1
value_track: True
value_track_color: root.cs
The .kv file that includes the submit button:
#: import statusbar StatusBar
<StatusBar#BoxLayout>
orientation:'horizontal'
padding: 5
fs: 16
Button:
text: 'Clear'
background_color: 0.0, 0.353, 0.663, 1.0
size_hint: 0.4, 1
bold: True
font_size: 20
on_press: root.btn_clear()
Button:
text: 'Submit'
background_color: 0.0, 0.353, 0.663, 1.0
size_hint: 0.4, 1
bold: True
font_size: 20
on_press: root.btn_submit()
and last but not the least the file that includes the methods that are assigned to the buttons, which shuld also be important for my issue:
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivy.app import App
from kivy.lang import Builder
class StatusBar(BoxLayout):
group_mode = False
#translation = ListProperty(None)
prozess = ObjectProperty(None)
vorbehandlung = ObjectProperty(None)
material = ObjectProperty(None)
haerte = ObjectProperty(None)
rauheit = ObjectProperty(None)
def btn_submit(self,text):
ip = App.get_running_app().root.ids._input_parameters
print("Haerte:", ip.haerte.value, "Rauheit:", ip.rauheit.value, "Material:", ip.material.text)
def btn_clear(self):
np = App.get_running_app().root.ids._input_parameters
np.prozess1.state = "normal"
np.prozess2.state = "normal"
np.prozess3.state = "normal"
np.material.text = "Auswahl treffen"
np.haerte.value = 55
np.rauheit.value = 5.5
The App is running like this and the clear button is exactly doing what its supposed to do, but I really can't figure out how I manage to print the selected spinner and toggle values when hitting submit...I hope you guys can help, been struggeling with this since a while now. Thanks in advance!
Alright i figured out an easy way to get the spinner value when hititng submit:
def btn_submit(self):
ip = App.get_running_app().root.ids._input_parameters
print("Haerte:", ip.haerte.value, "Rauheit:", ip.rauheit.value, "Material:", ip.material.text, "Vorbehandlung:", ip.vorbehandlung.text)
to get the value of the toggle buttons i did this:
def on_state(self, togglebutton):
tb = togglebutton
if tb.state == 'down':
self.verfahren = tb.text
InputParameters.verfahren = tb.text
print(self.verfahren)
return InputParameters.verfahren
and added in the .kv file for the toggle button:
ToggleButton:
id:_prozess2
text:'E-MOH'
on_state: root.on_state(self)
I'm getting the value/state like that, but it's not triggered with the submit button, can't figure out how to do so
I try to make a simple ToDoList program.There are add, remove and do it buttons. But I have some bugs about labels color. When I click "DO IT" button label color change in scrollview but when I click remove button when some of them done, colored labels change. I did using canvas. How can I fix this problem?
class Home(Screen):
def __init__(self,**kwargs):
super(Home,self).__init__(**kwargs)
def addWidget(self):
task_input = self.ids.task_input.text
newListItem = EachTask(text=task_input ,
id=str((len(self.ids.add_field.children))) )
print(newListItem.id)
self.ids.add_field.add_widget(newListItem)
class EachTask(BoxLayout):
def __init__(self, text= "", **kwargs):
super(EachTask,self).__init__(**kwargs)
self.ids.label.text = text
def Do_Task(self,instance):
child = instance.parent.parent
with self.canvas.before:
Color(.5,1,.2,1, mode='rgba')
Rectangle(pos=child.ids.label.pos, size=child.ids.label.size)
kv_file
<FlatButton#ButtonBehavior+Label>:
font_size: 15
<Home>:
BoxLayout:
id: home
orientation: "vertical"
spacing: 5
#space_x: self.size[0]/2
canvas.before:
Color:
rgba: (1,1,1,1)
Rectangle:
size: self.size
pos: self.pos
##########HEADER#######
BoxLayout:
id: header
size_hint_y: None
height: 50
canvas.before:
Color:
rgba: (.85,.7,.2,1)
Rectangle:
size: self.size
pos: self.pos
Label:
text: "TO DO LIST"
font_size: "20sp"
bold: True
size_hint_x: .9
FlatButton:
text: "Back"
size_hint_x: .1
####################################
ScrollView:
canvas.before:
Color:
rgba: (1,1,.2,.2)
Rectangle:
size: self.size
pos: self.pos
BoxLayout:
id: add_field
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
spacing: 2 #Spaces between childs
#####################################################
BoxLayout:
id: input_field
size_hint_y: None
height: 80
TextInput:
id: task_input
focus: True
size_hint_x: .9
multiline: False
Button:
font_size: "40sp"
size_hint_x: .1
text: "+"
on_release: root.addWidget()
id: button1
color: 1,0.5,0.5,1
#######################################################
<EachTask>:
size_hint_y: None
height: 50
id: each_task
BoxLayout:
Label:
size_hint_x: .8
id: label
canvas.before:
Color:
rgba: (1,.2,.2,.2)
Rectangle:
size: self.size
pos: self.pos
Button:
size_hint_x: .1
text: "X"
on_release: app.root.ids.add_field.remove_widget(root)
Button:
size_hint_x: .1
text: "DO IT"
on_release: root.Do_Task(self)
The following enhancements are required to the kv and py files to solve the problem.
Method 1 - Kivy automatically created & added an ObjectProperty, rgba
Kivy automatically created & added an ObjectProperty
If the widget doesn’t have a property with the given name, an
ObjectProperty will be automatically created and added to the widget.
kv file
Add a class attribute, rgba and initialize it to default colour, (1, .2, .2, .2) to class rule, <EachTask>:
Replace label's colour to root.rgba
Snippets - kv file
<EachTask>:
rgba: (1,.2,.2,.2) # Kivy auto created & added ObjectProperty, "rgba"
...
BoxLayout:
Label:
size_hint_x: .8
id: label
canvas.before:
Color:
rgba: root.rgba
...
py file
Remove all the codes in method Do_Task()
Add self.rgba = [.5, 1, .2, 1] whereby self refers to the current widget i.e. EachTask object.
Snippets - py file
def Do_Task(self, instance):
self.rgba = [.5, 1, .2, 1]
Method 2 - Explicitly declaring rgba
kv file
Replace rgba: (1,.2,.2,.2) with root.rgba
Snippets - kv file
<EachTask>:
...
BoxLayout:
Label:
size_hint_x: .8
id: label
canvas.before:
Color:
rgba: root.rgba
...
py file
Add import statement, from kivy.properties import ListProperty
Declare class attribute, rgba of ListProperty type and initilaize it to default colour, [1, .2, .2, .2] in class EachTask()
Remove all the codes in method Do_Task()
Add self.rgba = [.5, 1, .2, 1] whereby self refers to the current widget i.e. EachTask object.
Snippets - py file
from kivy.properties import ListProperty
...
class EachTask(BoxLayout):
rgba = ListProperty([1, .2, .2, .2])
...
def Do_Task(self, instance):
self.rgba = [.5, 1, .2, 1]
I was wondering how I could change the text of a label made inside the Kivy language using Python.
Like how would I have user input from python be made as the text of a label in kivy.
(By the way I have the formatting correct in the actual program but I screwed up pasting it to stackoverflow)
Say if I wanted to make the text of the label in from the code be a random number generated in python how would I go about doing that?
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.graphics import Color, Rectangle
from kivy.properties import ObjectProperty
# Create both screens. Please note the root.manager.current: this is how
# you can control the ScreenManager from kv. Each screen has by default a
# property manager that gives you the instance of the ScreenManager used.
Builder.load_string("""
<ButImage#ButtonBehavior+AsyncImage>
<TutImage#ButtonBehavior+AsyncImage>
<MenuScreen>:
GridLayout:
cols: 4
row_force_default: True
col_default_width: 175
row_default_height: 150
padding: 15
spacing: 15
canvas.before:
BorderImage:
# BorderImage behaves like the CSS BorderImage
border: 10, 10, 10, 10
source: '/Users/clayhigh/Desktop/kivy/aot.png'
pos: self.pos
size: self.size
Button:
text: 'Goto settings'
background_color: 1,0,0,0.5
on_press: root.manager.current = 'settings'
ButImage:
on_press: root.manager.current = 'UBW'
id: but
size_hint: .5, .5
opacity: 1 if self.state == 'normal' else .5
allow_stretch: True
keep_ratio: False
source: 'http://s3.amazonaws.com/rapgenius/1361742626_beautiful-ocean-beautiful-pictures-27115524-1440-900.jpg'
Label:
center: but.center
text: "UBW"
color: 0.78,0.145,0.016,2
ButImage:
id: lh
size_hint: .5, .5
opacity: 1 if self.state == 'normal' else .5
allow_stretch: True
keep_ratio: False
source: 'http://s3.amazonaws.com/rapgenius/1361742626_beautiful-ocean-beautiful-pictures-27115524-1440-900.jpg'
Label:
center: lh.center
text: "LH 2"
color: 0,0,0,1
ButImage:
id: ttl
size_hint: .5, .5
opacity: 1 if self.state == 'normal' else .5
allow_stretch: True
keep_ratio: False
source: 'http://s3.amazonaws.com/rapgenius/1361742626_beautiful-ocean-beautiful-pictures-27115524-1440-900.jpg'
Label:
center: ttl.center
text: "TwTl"
color: 0,0,0,1
ButImage:
id: gris
size_hint: .5, .5
opacity: 1 if self.state == 'normal' else .5
allow_stretch: True
keep_ratio: False
source: 'http://s3.amazonaws.com/rapgenius/1361742626_beautiful-ocean-beautiful-pictures-27115524-1440-900.jpg'
Label:
center: gris.center
text: "Gris"
color: 0,0,0,1
ButImage:
id: shig
size_hint: .5, .5
opacity: 1 if self.state == 'normal' else .5
allow_stretch: True
keep_ratio: False
source: 'http://s3.amazonaws.com/rapgenius/1361742626_beautiful-ocean-beautiful-pictures-27115524-1440-900.jpg'
Label:
center: shig.center
text: "Shig"
color: 0,0,0,1
Button:
text: 'Test3'
background_color: 1,0,0,0.5
Button:
text: 'Test4'
background_color: 1,0,0,0.5
Button:
text: 'Quit'
background_color: 1,0,0,0.5
on_press: App.on_stop
<SettingsScreen>:
GridLayout:
row_force_default: True
row_default_height: 100
cols: 2
canvas.before:
BorderImage:
# BorderImage behaves like the CSS BorderImage
border: 10, 10, 10, 10
source: '/Users/clayhigh/Desktop/kivy/ato.jpeg'
pos: self.pos
size: self.size
Button:
text: 'Button'
color: 0,0,.5
background_color: 1,0,0,1
Button:
text: 'Back to menu'
background_color: 1,0,0,1
on_press: root.manager.current = 'menu'
<UBW>:
GridLayout:
row_force_default: True
row_default_height: 100
cols: 2
canvas.before:
Color:
rgb: .5, .5, .5
Rectangle:
pos: self.pos
size: self.size
Color:
rgb: 1, 1, 1
BorderImage:
# BorderImage behaves like the CSS BorderImage
border: 10, 10, 10, 10
source: '/Users/clayhigh/Desktop/kivy/fsn.jpg'
pos: self.pos
size: self.size
Button:
text: 'Back to menu'
color: 0,0,.5
on_press: root.manager.current = 'menu'
background_color: 1,0,0,1
Label:
id: AName
text: "F S/N: UBW"
font_size: '24sp'
""")
# Declare both screens
class MenuScreen(Screen):
pass
class SettingsScreen(Screen):
pass
class UBW(Screen):
pass
# Create the screen manager
sm = ScreenManager()
sm.add_widget(MenuScreen(name='menu'))
sm.add_widget(SettingsScreen(name='settings'))
sm.add_widget(UBW(name='UBW'))
class TestApp(App):
def build(self):
return sm
if __name__ == '__main__':
TestApp().run()
Text of a label can be a kivy property, which can be later changed and since it is a kivy property it will automatically updated everywhere. Here is an example of your .py
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import StringProperty
import random
class YourWidget(Widget):
random_number = StringProperty()
def __init__(self, **kwargs):
super(YourWidget, self).__init__(**kwargs)
self.random_number = str(random.randint(1, 100))
def change_text(self):
self.random_number = str(random.randint(1, 100))
class YourApp(App):
def build(self):
return YourWidget()
if __name__ == '__main__':
YourApp().run()
and your .kv
<YourWidget>:
BoxLayout:
size: root.size
Button:
id: button1
text: "Change text"
on_release: root.change_text()
Label:
id: label1
text: root.random_number
When you click the button, it will call change_text() function, which will randomly change the text of the label to random integer between 1 and 100.