How to add custom widget to another custom widget in kivy - python

I am pretty new to the kivy language and faced this problem when try to run the following code. it just runs without any errors. But it just only generate a blank application. without any widgets.
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager
from kivy.uix.gridlayout import GridLayout
from kivymd.uix.boxlayout import MDBoxLayout
kv = """
<SCManager>:
Screen:
c_screen:
<c_screen>:
cols: 2
canvas.before:
Color:
rgba: 1,0,0,1
Rectangle:
pos: self.pos
size: self.size
MDBoxLayout:
md_bg_color: (1, 1, 1 ,1)
padding: 10
adaptive_height: True
MDLabel:
text: "helow 2"
color: (0.0003, 0.34, 0.60,1)
font_style: "H6"
halign: "left"
adaptive_height: True
<navigator>:
canvas.before:
Color:
rgba: 1,1,0,1
Rectangle:
pos: self.pos
size: self.size
orientation: "vertical"
MDLabel:
text: "hellow"
adaptive_height: True
MDList:
OneLineAvatarListItem:
text : "Dashboard"
IconLeftWidgetWithoutTouch:
icon: "view-dashboard"
OneLineAvatarListItem:
text : "Manage Users"
IconLeftWidgetWithoutTouch:
icon: "account"
MDRoundFlatIconButton:
text: "bye"
font_size: 11
"""
class SCManager(ScreenManager):
pass
class navigator(MDBoxLayout):
pass
class c_screen(GridLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.n = navigator()
self.add_widget(self.n)
class test(MDApp):
def build(self):
Builder.load_string(kv)
return SCManager()
if __name__ == '__main__':
test().run()
But if i add another widget(a label) to Screen from kv string, it works fine or if i use add_widget(c_screen) in SCManager it works fine.But i need to add c_screen class from the kv string. Is there any way to add widgets without adding any widgets to Screen??
here is the working code
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager
from kivy.uix.gridlayout import GridLayout
from kivymd.uix.boxlayout import MDBoxLayout
kv = """
<SCManager>:
Screen:
MDLabel:
text: "helow 2"
adaptive_height: True
c_screen:
<c_screen>:
cols: 2
canvas.before:
Color:
rgba: 1,0,0,1
Rectangle:
pos: self.pos
size: self.size
MDBoxLayout:
md_bg_color: (1, 1, 1 ,1)
adaptive_height: True
MDLabel:
text: "helow 2"
adaptive_height: True
<navigator>:
canvas.before:
Color:
rgba: 1,1,0,1
Rectangle:
pos: self.pos
size: self.size
orientation: "vertical"
MDLabel:
text: "hellow"
adaptive_height: True
MDList:
OneLineAvatarListItem:
text : "Dashboard"
IconLeftWidgetWithoutTouch:
icon: "view-dashboard"
OneLineAvatarListItem:
text : "Manage Users"
IconLeftWidgetWithoutTouch:
icon: "account"
MDRoundFlatIconButton:
text: "bye"
font_size: 11
"""
class SCManager(ScreenManager):
pass
class navigator(MDBoxLayout):
pass
class c_screen(GridLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.n = navigator()
self.add_widget(self.n)
class test(MDApp):
def build(self):
Builder.load_string(kv)
return SCManager()
if __name__ == '__main__':
test().run()

Related

How Can I Remove BoxLayout?

I want to remove a Boxlayout in my widget, but I cant.
There is a Boxlayout at the begining of the app called "Speca". After my sellections it must be removed.
When you run the app, sellect something in "Home" Spinner and click any of the new Toggle buttons.
Wtih the press of any of the Toggle buttons "Speca" must disappear.
Please help.
Here is main.py:
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.scrollview import ScrollView
from kivy.uix.spinner import Spinner
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.properties import ObjectProperty, StringProperty, BooleanProperty
from kivy.properties import ListProperty
from collections import OrderedDict
from kivy.uix.togglebutton import ToggleButton
data1=["mother","father","son"]
data2=["uncle","aunt","grandfather"]
data3=["jack","mike","simon"]
data4=["1898","1975","1985","1885"]
amd="0dp"
class MainWidget(Widget):
def remove_layout(self, *ignore):
self.remove_widget(self.layout)
global amd
an0=tuple(list(OrderedDict.fromkeys(data1)))
cal5= ObjectProperty()
cal6= ObjectProperty()
def btn10(self,text):
if self.cal5:
self.cal5.parent.remove_widget(self.cal5)
self.cal5 =ModelSpecifications()
a=data2
b=data3
c=data4
mi=[]
n=0
while n < len(a):
aba=n
mi.append(aba)
n+=1
for i in mi:
self.b1=MyTButton(text=str(i),size_hint=(1,None),height="100dp",group="selections")
self.cal5.add_widget(self.b1)
self.ids.scd.add_widget(self.cal5, index=3)
def on_state(self, togglebutton): #<----THIS IS THE TUGGLEBUTTON I WANT USE
global amd
tb = togglebutton
text1=tb.text
if text1=="0":
amd="50dp"
elif text1=="1":
amd="100dp"
else:
amd="200dp"
if self.cal6:
self.cal6.parent.remove_widget(self.cal6)
self.cal6 =Spec()
self.ids.scd.add_widget(self.cal6, index=2)
class SecondPage(ScrollView):
pass
class Speca(BoxLayout): #<------ THIS IS THE BOXLAYOUT I WANT TO REMOVE
pass
class Spec(BoxLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.size_hint=(1,None)
self.height=amd
class MyTButton(ToggleButton):
def __init__(self, **kwargs):
super().__init__(**kwargs)
class ModelSpecifications(BoxLayout): #this is the class I want add after my spinner selection
pass
class Calculation(GridLayout):
pass
class MyApp(App):
pass
MyApp().run()
here is my.kv :
MainWidget:
<MainWidget>:
hideable: hideable
ScreenManager:
id: scmanager
size: root.width, root.height
Screen:
id: scndpage
name: "second"
SecondPage:
Calculation:
id:scd
cols:1
height: self.minimum_height
row_default_height: "70dp"
size_hint_y: None
spacing:"10dp"
canvas.before:
Rectangle:
pos: self.pos
size: self.size
BoxLayout:
size_hint: 1, None
height: "50dp"
pading:"10dp"
spacing:"10dp"
orientation: "vertical"
BoxLayout:
orientation: "horizontal"
Label:
text:"Name:"
color: 0,0,0,1
TextInput:
text:"---"
color: 0,0,0,1
Label:
text:"Surname:"
color: 0,0,0,1
TextInput:
text:"-----"
color: 0,0,0,1
BoxLayout:
id:scdd
size_hint: 1, 1
height: "100dp"
orientation: "vertical"
BoxLayout:
size_hint: 1, None
height: "50dp"
orientation: "horizontal"
Label:
text: " Sellection:"
color: 0,0,0,1
Spinner:
text: 'Home'
values: root.an0
on_text: app.root.btn10(self.text)
Speca: #<------ THIS IS THE BOXLAYOUT I WANT TO REMOVE
Button:
text:" Calculate"
Button:
text:"Sellect"
Button:
text:"Back"
<ModelSpecifications>:
id:anss
pading:"10dp"
spacing:"10dp"
size_hint: 1, None
height: "100dp"
orientation: "horizontal"
<MyTButton#ToggleButton>: #<----THIS IS THE TUGGLEBUTTON I WANT USE
on_state:
app.root.on_state(self)
<Speca>: #<------ THIS IS THE BOXLAYOUT I WANT TO REMOVE
orientation:"vertical"
Label:
color: (1,1,0,1)
text:"I WANT TO REMOVE THIS PART WHEN I PRESS ANY OF TOGGLE BUTTONS"
Please run the app and see it.
Looks to me like speca is a child of the calculation widget with ID scd. So give speca an ID and then Remove speca via ids in on_srate python function.
Kv
SecondPage:
Calculation:
id:scd
speca:
id: speca
py
def on_state():
self.root.ids.scd.remove_widget(self.root.ids.speca)
YES.
When I make those changes;
Kv
SecondPage:
Calculation:
id:scd
speca:
id: speca
py
def on_state():
self.ids.scd.remove_widget(self.ids.speca)
It works.

How can I change the height of Boxlayout Dynamically?

I am trying to change Boxlayout height dynamically. There will an empty Boxlayout at the beginning, then with a ToggleButton I will add Buttons on that Boxlayout vertically. But this Boxlayout locates in Gridlayout which has ScrollView. And the number of buttons I will add will change, so the height of the box layout should change too. But it doesn't change. Could you please help.
Here is my main.py:
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.scrollview import ScrollView
from kivy.uix.spinner import Spinner
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.properties import ObjectProperty, StringProperty, BooleanProperty
from kivy.properties import ListProperty
from collections import OrderedDict
data1=["mother","father","son"]
data2=["uncle","aunt","grandfather"]
data3=["jack","mike","simon"]
data4=["1898","1975","1985","1885"]
class MainWidget(Widget):
an0=tuple(list(OrderedDict.fromkeys(data1)))
cal5= ObjectProperty()
def btn10(self,text):
if self.cal5:
self.cal5.parent.remove_widget(self.cal5) #EVERY TIME I NEED TO REMOVE IT BECAUSE MY BUTTON QUANTITIY AND TEXT WILL CHANGE DUE TO TOGGLE BUTTON SELECTION
self.cal5 =ModelSpecifications()
a=data2
b=data3
c=data4
mi=[]
n=0
while n < len(a):
aba=(str(a[n])+"\n"+str(b[n])+"\n"+str(c[n]))
mi.append(aba)
n+=1
for i in mi:
self.b1=Button(text=str(i),size_hint=(1,None),height="10dp")
self.cal5.add_widget(self.b1)
self.ids.scd.add_widget(self.cal5, index=3) #I ADD THE BUTTONS IN HERE
class SecondPage(ScrollView):
pass
some_number=120
calculated_height=(str(some_number)+"dp") #<------I CAN CHANGE THE HEIGHT AT THE BEGINING BUT IT DOSENT CHANGE THE HEIGHT DYNAMICALLY
class ModelSpecifications(BoxLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.size_hint=(1,None)
self.height=calculated_height
class Calculation(GridLayout):
pass
class MyApp(App):
pass
MyApp().run()
And here is my my.kv file:
#:import C kivy.utils.get_color_from_hex
MainWidget:
<MainWidget>:
ScreenManager:
id: scmanager
size: root.width, root.height
Screen:
id: scndpage
name: "second"
SecondPage:
Calculation:
id:scd
cols:1
height: self.minimum_height
row_default_height: "70dp" #<---THIS HEIGHT MUST BE SPECIFY BECAUSE OF SCROLLWIEW
size_hint_y: None
spacing:"10dp"
canvas.before:
Rectangle:
pos: self.pos
size: self.size
BoxLayout:
size_hint: 1, None
height: "50dp"
pading:"10dp"
spacing:"10dp"
orientation: "vertical"
BoxLayout:
orientation: "horizontal"
Label:
text:"Name:"
color: 0,0,0,1
TextInput:
text:"---"
color: 0,0,0,1
Label:
text:"Surname:"
color: 0,0,0,1
TextInput:
text:"-----"
color: 0,0,0,1
BoxLayout:
id:scdd
size_hint: 1, 1
height: "100dp"
orientation: "vertical"
BoxLayout:
size_hint: 1, None
height: "50dp"
orientation: "horizontal"
Label:
text: " Sellection:"
color: 0,0,0,1
Spinner:
text: 'Home'
values: root.an0
on_text: app.root.btn10(self.text)
Button:
text:" Calculate"
Button:
text:"Sellect"
Button:
text:"Back"
<ModelSpecifications>: #<---------HOW CAN I DYNAMICALLY CHANGE THE HEIGHT OF THIS WIDGET ?
id:anss
pading:"10dp"
spacing:"10dp"
orientation: "vertical"
canvas.before:
Color:
rgba: (C('EBE4E4'))
RoundedRectangle:
size: self.size
pos: self.pos
radius: [15]
I want to change the height in the python script because I will get the information from another function as variable.
Please run the file. Looking forward to your comments.

Using entries from other kivy classes

I am a beginner in Language and I am trying to make a simple guessing game and I would like to know how I use the data entered in the Players Class in the Start_p1 Class. I want the name typed in the TextInput of the Players Class, to appear in the Label Text: of the Start_p1 Class.
Arquivo .py:
import kivy
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.uix.textinput import TextInput
from kivy.properties import StringProperty
class Home(Screen):
def next(self):
self.manager.current = "players"
class Players(Screen):
def start(self):
self.manager.current = 'st1'
class Start_p1(Screen):
def runn(self):
self.manager.current = 'st2'
class Start_p2(Screen):
def back(self):
self.manager.current = 'st1'
class Finish(Screen): pass
class Myapp(App):
sm = None
def build(self):
self.sm = ScreenManager()
self.sm.add_widget(Home(name = 'home'))
self.sm.add_widget(Players(name = 'players'))
self.sm.add_widget(Start_p1(name = 'st1'))
self.sm.add_widget(Start_p2(name = 'st2'))
self.sm.add_widget(Finish(name = 'finish'))
self.sm.current = 'home'
return self.sm
if __name__ == '__main__':
Myapp().run()
Arquivo.kv
#: import utils kivy.utils
<Home>:
FloatLayout:
canvas.before:
Color:
rgb: utils.get_color_from_hex('#2169af')
Rectangle:
pos: self.pos
size: self.size
Button:
text: 'Iniciar'
pos_hint: {'center_x': .5, 'center_y': .5}
size_hint: 0.2, .1
background_color: utils.get_color_from_hex('#13447d')
on_release: root.next()
Button:
text: 'Configurações'
pos_hint: {'center_x': .5, 'center_y': .4}
size_hint: 0.2, .1
background_color: utils.get_color_from_hex('#13447d')
<Players>:
FloatLayout:
canvas.before:
Color:
rgb: utils.get_color_from_hex('#2169af')
Rectangle:
pos: self.pos
size: self.size
Label:
pos: 0, 270
text: 'JOGADORES'
Label:
pos: 0, 150
text: 'Informe o nome do 1° Jogador:'
TextInput:
id: txtt
pos: 270, 400
size: 250, 30
multiline: False
Label:
pos: 0, -20
text: 'Informe o nome do 2° Jogador:'
TextInput:
id: txt
pos: 270, 230
size: 250, 30
multiline: False
Button:
text: 'Iniciar'
pos_hint: {'center_x': .5, 'center_y': .2}
size_hint: 0.2, .1
background_color: utils.get_color_from_hex('#13447d')
on_release: root.start()
<Start_p1>:
Players:
id: players
FloatLayout:
canvas.before:
Color:
rgb: utils.get_color_from_hex('#2169af')
Rectangle:
pos: self.pos
size: self.size
Label:
text:
That is actually a bit tricky. One would expect that you can use:
Label:
text: app.sm.get_screen('players').ids.txt.text
That will technically work, but it won't set up the automatic update if the text of the TextInput changes. A careful reading the documentation explains why, and suggests a work around. Using the suggestion from the documentation, you can do something like this:
Label:
players_screen: app.sm.get_screen('players')
text: self.players_screen.ids.txt.text
This produces the desired result with automatic updates.

How do you change the background color of a TabbedPanelItem in Kivy

I want to change the background color on my tabs and change from the default grey color, but I can't manage to find out how to do it.
I have tried defining a canvas but that just ends up creating like a colored layer over the tab and then I can't read the text on the tab.
my .py file:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
class IntroScreen(Screen):
pass
class MainScreen(Screen):
pass
class ScreenManagement(ScreenManager):
pass
app=Builder.load_file("main.kv")
class mainApp(App):
def build(self):
return app
mainApp().run()
main.kv file:
#: import FadeTransition kivy.uix.screenmanager.FadeTransition
#: import get_color_from_hex kivy.utils.get_color_from_hex
ScreenManagement:
transition: FadeTransition()
MainScreen:
<MainScreen>:
name: "main_screen"
BoxLayout:
orientation: "horizontal"
height: 30
BoxLayout:
orientation: "horizontal"
TabbedPanel:
do_default_tab: False
tab_width: self.parent.width/2
canvas.before:
Color:
rgb: get_color_from_hex("#ffffff")
Rectangle:
size: self.size
pos: self.pos
TabbedPanelItem:
text: "Tab 1"
color: get_color_from_hex("#ffffff")
markup: True
Label:
text: "contents of tab 1"
color: get_color_from_hex("#000000")
canvas.before:
Color:
rgb: get_color_from_hex("#ffffff")
Rectangle:
size: self.size
pos: self.pos
TabbedPanelItem:
text: "Tab 2"
markup: True
Label:
text: "contents of tab 2"
color: get_color_from_hex("#000000")
canvas.before:
Color:
rgb: get_color_from_hex("#ffffff")
Rectangle:
size: self.size
pos: self.pos
The tab is a class of TabbedPanelHeader and they have the following properties just like Button widget.
Example
Add the following into kv file:
<TabbedPanelHeader>:
background_normal: 'blue.png'
background_down: 'red.png'
Output

No Screen with name

All my program works up-to a point and I'm road blocked by it.
My program loads some starter screens in the main app.
Based on user input the program loads a completely different sub app.
Problem occurs when trying to change screens in the loaded sub app
Here is the code where the problem exists:
The .py file:
import kivy
kivy.require('1.10.0')
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen, ScreenManager, FadeTransition
from kivy.uix.button import Button
from kivy.uix.label import Label
chClass = ""
class ScreenManage(ScreenManager):
pass
class Home(ScreenManager):
pass
class TitleScreen(Screen):
pass
class GameScreen(Screen):
pass
class ClassScreen(Screen):
pass
class Warrior1(Screen):
def GetChClass(self, ch):
return ch
def build(self):
ExecuteW().run()
class Acrobat1(Screen):
def GetChClass(self, ch):
return ch
class Spell1(Screen):
def GetChClass(self, ch):
return ch
class HomeScreen(Screen):
pass
class WarriorStats(Screen):
pass
class AcrobatStats(Screen):
pass
class SpellCasterStats(Screen):
pass
class ExecuteW(App):
def build(self):
return Home()
class RevengeApp(App):
def build(self):
return ScreenManage()
if __name__ == '__main__':
print chClass
RevengeApp().run()
revenge.kv:
#: import sm kivy.uix.screenmanager
#: import Factory kivy.factory.Factory
#: import builder kivy.lang.Builder
<ScreenManage>
transition: sm.FadeTransition()
TitleScreen:
ClassScreen:
GameScreen:
Warrior1:
Acrobat1:
Spell1:
WarriorStats:
<TitleScreen>
on_touch_down: app.root.current = 'Game'
canvas:
Rectangle:
size: self.size
pos: self.pos
source: 'KnightArmor.jpg'
BoxLayout:
orientation: 'vertical'
Label:
font_size: '30sp'
color: 1,0,0,1
text: "Warrior's Revenge"
Label:
color: 1,0,0,1
text: "Click to Continue:"
<GameScreen>
name: 'Game'
canvas:
Rectangle:
size: self.size
pos: self.pos
source: 'KnightArmor.jpg'
BoxLayout:
Button:
size_hint: .5,.1
text: "New Game"
on_release: app.root.current = 'Class'
Button:
size_hint: .5,.1
text: "Load Game"
<ClassScreen>
name: 'Class'
BoxLayout:
orientation: 'vertical'
Label:
text: "Choose Your Path"
Button:
text: "Warrior"
on_release: app.root.current = "Warrior1"
Button:
text: "Acrobat"
on_release: app.root.current = "Acrobat1"
Button:
text: "Spell Caster"
on_release: app.root.current = "Spell1"
<Warrior1>
name: "Warrior1"
canvas:
Rectangle:
size: self.size
pos: self.pos
source: "Warrior.jpg"
BoxLayout:
orientation: 'vertical'
Label:
font_size: "20sp"
text: "Warrior's are physically strong"
color: 0,.5,1,1
Label:
font_size: "20sp"
text: "experts in hand to hand combat,"
color: 0,.5,1,1
Label:
font_size: "20sp"
text: "and knowledgeable in the ways of"
color: 0,.5,1,1
Label:
font_size: "20sp"
text: "arms and armor"
color: 0,.5,1,1
BoxLayout:
orientation: 'horizontal'
Button:
text: "Cancel"
on_release: app.root.current = "Class"
Button:
name: "warrior_confirm"
text: "Confirm"
on_release: chClass = root.GetChClass('Warrior')
on_release: root.build()
executew.kv:
#: import sm kivy.uix.screenmanager
<Home>:
transition: sm.FadeTransition()
HomeScreen:
WarriorStats:
<HomeScreen>
name: 'Home'
AnchorLayout:
Button:
text: "Stats"
on_release: app.root.current = 'WStats'
<WarriorStats>
name: 'WStats'
canvas:
Rectangle:
size: self.size
pos: self.pos
source: "Warrior.jpg"
The problem:
When clicking the stats button on the home screen in executew the WarriorStats screen named 'WStats' should be loaded, but I get the error "no screen with name 'WStats'"
Answer that I figured out on my own
class HomeScreen(Screen):
def switch(self):
self.manager.current = "WStats"
And in executew:
<HomeScreen>
Button:
text: "Stats"
on_release: root.switch()

Categories