Button that delete itself - python

My idea its create a order list. This have to be posible of expand or reduce if the order needed. So I was trying how to do a button that can add a 'Box Label' to a grid, at the same time that this 'Box Label' have the property of delete by itself by a button. I tried a lot of things, but I am really new in this, so nothing work for me.
class OperatorWindow(BoxLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
Window.size = (1366, 768)
def remove_item(self):
self.ids.parent.clear_widgets()
def add_more(self):
prod_addmore = self.ids.product_inputs
product = BoxLayout(size_hint_x=1, height=30, spacing=5)
prod = TextInput(size_hint_x=.2)
qty = TextInput(size_hint_x=.1)
price = TextInput(size_hint_x=.1)
delete = Button(text='-', size_hint_x=.05)
product.add_widget(prod)
product.add_widget(qty)
product.add_widget(price)
product.add_widget(delete)
prod_addmore.add_widget(product)
delete.bind(on_release=self.deleting(prod_addmore, product))
def deleting(self, prod_addmore, product):
prod_addmore.remove_widget(product)
class OperatorApp(App):
def build(self):
return OperatorWindow()
if __name__ == "__main__":
oa = OperatorApp()
oa.run()
Kivy File
...
BoxLayout:
id: products_labels
size_hint_y: None
size_hint_x: .45
height: 40
spacing: 5
FlatButton:
size_hint_x: .2
text: 'Producto'
canvas.before:
Color:
rgba: (.30,.30,.30,1)
Rectangle:
size: self.size
pos: self.pos
FlatButton:
size_hint_x: .1
text: 'Cantidad'
canvas.before:
Color:
rgba: (.30,.30,.30,1)
Rectangle:
size: self.size
pos: self.pos
FlatButton:
size_hint_x: .1
text: 'Precio'
canvas.before:
Color:
rgba: (.30,.30,.30,1)
Rectangle:
size: self.size
pos: self.pos
FlatButton:
text: '+'
size_hint_x: .05
on_release: root.add_more()
canvas.before:
Color:
rgba: (.30,.30,.30,1)
Rectangle:
size: self.size
pos: self.pos
ScrollView:
size_hint_y: .15
do_scroll_x: False
do_scroll_y: True
GridLayout:
id: product_inputs
size:(self.width, self.height)
size_hint_x: .45
spacing: 5
size_hint_y: None
cols: 1
height: self.minimum_height
row_default_height: 30
row_force_default: True

Please refer to this link! For some refreshers about widgets.
Your code is fine you just need some minor adjustments here and there.
Firstly change
product
To
self.product
It always makes it easier to call functions since the self indicates ownership okay.
Secondly change this line
delete.bind(on_release=self.deleting(prod_addmore, product))
to
delete.bind(on_release=self.deleting)
the reason for the error is because of the parenthesis. And lastly
Chang this
def deleting(self, prod_addmore, product):
prod_addmore.remove_widget(product)
to
def deleting(self, widget):
prod_addmore = self.ids.product_inputs
prod_addmore.remove_widget(self.product)
Hope this helps if you need more indept explano please let me know :)

Related

Kivy how to have one class and method for multiple dropdowns?

I am making an app where I will have many different labels for dropdown lists. These dropdown lists will be activated by a button that will show the dropdown.
My problem is that I do not know how to have multiple dropdowns using only one class in my python code. Currently, I have to make multiple classes and multiple methods to activate different dropdown menus and to have those dropdown menus come from different classes.
Trying to modify the show_dropDown() didn't work since i couldn't get the labels to show and the button to link the dropdown menu from.
main.py
from kivy.app import App
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.dropdown import DropDown
from kivy.uix.gridlayout import GridLayout
from kivy.uix.screenmanager import Screen
Window.size = (286.110236, 570.33070866)
class HomeScreen(Screen):
pass
class CustomDropDown(DropDown):
pass
class CustomDropDown2(DropDown):
pass
class ButtonGrid(ButtonBehavior, GridLayout):
def show_dropDown(self):
dropdown = CustomDropDown()
dropdown.open(self)
def show_dropDown2(self):
dropdown = CustomDropDown2()
dropdown.open(self)
GUI = Builder.load_file("main.kv")
class MainApp(App):
def build(self):
return GUI
MainApp().run()
kv-file:
#:import utils kivy.utils
#:import Factory kivy.factory.Factory
<ButtonGrid>:
<CustomDropdown>:
id: dropdown
Label:
id: label1
text: 'Dropdown 1'
size_hint_y: None
height: 400
background_color: (0, 1, 0, .9)
canvas.before:
Color:
rgba: self.background_color
Rectangle:
size: self.size
pos: self.pos
<CustomDropdown2>:
id: dropdown2
Label:
id: label2
text: 'Dropdown 2'
size_hint_y: None
height: 400
background_color: (1, 0, 1, .9)
canvas.before:
Color:
rgba: self.background_color
Rectangle:
size: self.size
pos: self.pos
<HomeScreen>:
FloatLayout:
canvas:
Color:
rgb: utils.get_color_from_hex("#FFFFFF")
Rectangle:
size: self.size
pos: self.pos
GridLayout:
rows: 8
cols: 1
spacing: 10
size_hint_y: None
height: 1200
width: self.minimum_width
ButtonGrid:
id: button1
cols:1
rows:1
size_hint: 1, None
height: 185.71
on_press:
self.show_dropDown()
background_color: (1,0,0,1)
canvas.before:
Color:
rgba: self.background_color
Rectangle:
size: self.size
pos: self.pos
Label:
text: "Button 1"
ButtonGrid:
id: button2
cols:1
rows:1
size_hint: 1, None
height: 185.71
on_press:
self.show_dropDown2()
background_color: (0,0,1,1)
canvas.before:
Color:
rgba: self.background_color
Rectangle:
size: self.size
pos: self.pos
Label:
text: "Button 2"
You can add property (or properties) to your CustomDropDown class (or may be to ButtonGrid) and link it to associated widget as follows:
First in .py
class CustomDropDown(DropDown):
text = StringProperty("")
Then in .kv
<CustomDropdown>:
id: dropdown
Label:
id: label1
text: root.text
size_hint_y: None
...
Now call them as you need with some added args/kwargs,
...
GridLayout:
rows: 8
cols: 1
spacing: 10
size_hint_y: None
height: 1200
width: self.minimum_width
ButtonGrid:
id: button1
cols:1
rows:1
size_hint: 1, None
height: 185.71
on_press:
self.show_dropDown('Dropdown 1')
background_color: (1,0,0,1)
canvas.before:
Color:
rgba: self.background_color
Rectangle:
size: self.size
pos: self.pos
Label:
text: "Button 1"
ButtonGrid:
id: button2
cols:1
rows:1
size_hint: 1, None
height: 185.71
on_press:
self.show_dropDown(value='Dropdown 2')
background_color: (0,0,1,1)
And handle those calls in one go,
class ButtonGrid(ButtonBehavior, GridLayout):
def show_dropDown(self, value = ""):
dropdown = CustomDropDown(text = value)
dropdown.open(self)

Widgets in recycleview of variable height overlapping (Kivy)

After a question that was answered yesterday, this code can now set the height of the layout/widgets within the recycle view correctly. However, after 1 or 2 updates to the list, the widgets overlap. This is vital to my app working and it is super close.
I read in the Kivy documentation that the recycle view reuses widgets, which is why it is more efficient than the scroll view. However, I have not been able to understand what it means by reusing them, or how it may affect my program.
I would encourage anyone, who thinks they may be able to help, to run the code below to get a better understanding of what I have attempted to describe, but any comments, pointers, or solutions will be massively apreciated.
What currently works:
The new layouts that contain widgets are added to the recycle view successfully
The layouts resize correctly to fit the amount of text they contain
What doesn't currently work
The layouts with widgets moving to the correct position and not overlapping
main.py
from kivy.app import App
from kivy.properties import ListProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.recycleview.views import RecycleDataViewBehavior
example_string = 'jshdfjhsdkjfhjkshfjkshjfhsjkdhfkjshfkjshdfjkshjkdfhsjkdhfkjshfjhsjkfhskjhfjkhfkjhdjfkhsjdkhfkjshdkjhsdjhfsjkdhfjkshdjkfhsdkjhfjksdhfkjshdf)£++£(0'
class MASTER(BoxLayout):
def example_button(self, Button): # Demo of list updating
global example_string # I know
example_string += ')+££+(test\n\n\nsdhfsjdgfj)£++£(0'
temp = []
id_num = 0
for post in example_string.split(')+££+('): # The string is an example of the input data
temp.append({'message_id':id_num, 'text':('[font=Nunito-Bold.ttf][color=161616]Someone:[/color][/font]\n' + post.split(')£++£(')[0]), '_group':str(id_num), '_score':int(post.split(')£++£(')[1])})
id_num = id_num + 1
App.get_running_app().posts = temp
class DemoApp(App):
# One post format = {'message_id':0, 'text':'post_test_here','_size':[0,0], '_group':str(0), '_score':20}
# Text fromat string = [font=Nunito-Bold.ttf][color=161616]Someone:[/color][/font]\n
posts = ListProperty([])
def up_vote(self, button, mode): # Not part of the problem
if button.state == 'down':
if mode == 'all':
print("+1 upvote for message index:" + str(button.parent.parent.message_id) + ' in all posts')
else:
print("+1 upvote for message index:" + str(button.parent.parent.message_id) + ' in top posts')
def down_vote(self, button, mode): # Not part of the problem
if button.state == 'down':
if mode == 'all':
print("-1 upvote for message index:" + str(button.parent.parent.message_id) + ' in all posts')
else:
print("-1 upvote for message index:" + str(button.parent.parent.message_id) + ' in top posts')
if __name__ == '__main__':
DemoApp().run()
demo.kv
MASTER:
<MASTER>:
Button:
text: 'Add items'
on_press: root.example_button(self)
RecycleView:
viewclass: 'PostGrid'
scroll_y: 1
id: rv
data: app.posts
canvas.before:
Color:
rgba: 0, 0, 0, 1
Rectangle:
pos: self.pos
size: self.size
RecycleBoxLayout:
id: box
default_size_hint: 1, None
default_size: None, dp(50) #
size_hint_y: None
padding: ["10dp", "16dp"]
spacing: "20dp"
height: self.minimum_height
orientation: 'vertical'
<PostGrid#BoxLayout>:
message_id: -1
orientation: "horizontal"
text: ''
_group: ''
_score: 0
spacing: "6dp"
text_size: None, None
size_hint_y: None
height: self.minimum_height
BoxLayout:
id: voting_menu
orientation: "vertical"
spacing: "2dp"
size_hint: .2, None
height: label.height # This binding will force voting_menu to resize.
# size: self.size # I don't think it has any effect.
ToggleButton:
id: button_up
on_state: app.up_vote(self, 'all')
group: str(root._group)
text: "UP"
color: (1,1,1,1) if self.state=='normal' else (.8,0,0,1)
font_size: "10dp"
size_hint: 1, .3
background_color: .2, .2, .2, 0
canvas.before:
Color:
rgba: (.1,.1,.1,1)
RoundedRectangle:
pos: self.pos
size: self.size
radius: [6,]
canvas:
Color:
rgba: .2,.2,.2,1
Line:
width: 1.4
rounded_rectangle:(self.x,self.y,self.width,self.height, 5)
Label:
id: vote_count
text: str(root._score)
size_hint: 1, .4
multiline: False
ToggleButton:
id: button_down
on_state: app.down_vote(self, 'all')
group: str(root._group)
text: "DOWN"
color: (1,1,1,1) if self.state=='normal' else (.8,0,0,1)
font_size: "10dp"
size_hint: 1, .3
background_color: .2, .2, .2, 0
canvas.before:
Color:
rgba: (.1,.1,.1,1)
RoundedRectangle:
pos: self.pos
size: self.size
radius: [6,]
canvas:
Color:
rgba: (.2,.2,.2,1)
Line:
width: 1.4
rounded_rectangle:(self.x,self.y,self.width,self.height, 5)
Label:
id: label # For reference.
text: root.text
padding: "10dp", "12dp"
size_hint: .9, None
height: self.texture_size[1]
font_size: "12dp"
text_size: self.width, None
color: 0,0,0,1
multiline: True
markup: True
# on_texture_size: app.update_message_size(root.message_id, self.texture_size)
pos: self.x, self.y
canvas.before:
Color:
rgba: (0.8, 0.8, 0.8, 1)
RoundedRectangle:
size: self.texture_size
radius: [5, 5, 5, 5]
pos: self.x, self.y
canvas:
Color:
rgba:0.8,0,0,1
Line:
width: 1.4
rounded_rectangle:(self.x,self.y,self.width,self.height, 5)
Image of overlap
Guesses
Adding items instead of updating all of the items stored in 'posts' at once
Finding a way to refresh the recycleview to update the widgets
Creating a custom widget in place of the widgets in layouts for every item in the recycleview
This is a strange problem. I noticed that you are using self.minimum_height and label.height to try to adjust the size, and I believe your code should work. But it only seems to work sometimes. I have added a hack to work around this problem by setting the height of the PostGrid instances via python code. Here is that hack:
class MASTER(BoxLayout):
def example_button(self, Button): # Demo of list updating
global example_string # I know
example_string += ')+££+(test\n\n\nsdhfsjdgfj)£++£(0'
temp = []
id_num = 0
for post in example_string.split(')+££+('): # The string is an example of the input data
temp.append({'message_id': id_num, 'text': (
'[font=Roboto-Bold.ttf][color=161616]Someone:[/color][/font]\n' + post.split(')£++£(')[0]),
'_group': str(id_num), '_score': int(post.split(')£++£(')[1])})
id_num = id_num + 1
App.get_running_app().posts = temp
Clock.schedule_once(self.fix_sizes)
def fix_sizes(self, dt):
rbl = self.ids.box
for w in rbl.walk():
if isinstance(w, Factory.PostGrid):
w.height = max(w.ids.label.height, w.ids.voting_menu.height)

Kivy: Radio button correct implementation

My App has 3 screens to navigate through with the 'ActionBar'. I have named each screen in kv file, one is 'track' the other 'pess'. These are the two I need help with.
I created a radiobutton widget in my 'pess' screen class (pictures below) So I could add email address.
In my 'track' screen class I have all the data I'd like to send over email but I think I'm over complicating things. I want to link the active radiobutton from my 'pess' screen to my 'track' screen def send function...
my Main.py looks like this
class ScreenGenerator(ScreenManager):
pass
class PessQuestions(Screen):
email = {}
path = ''
def loadEmails(self, *args):
self.path = App.get_running_app().user_data_dir + '/'
try:
with open(self.path + 'email.json', 'r') as data:
self.email = json.load(data)
except FileNotFoundError:
pass
def saveEmails(self, *args):
print(self.ids.name.text, type(self.ids.name.text))
print(self.ids.address.text, type(self.ids.address.text))
self.email[self.ids.name.text] = self.ids.address.text
self.path = App.get_running_app().user_data_dir + '/'
with open(self.path + 'email.json', 'w') as email_address_json:
json.dump(self.email, email_address_json)
print('saveEmails')
self.ids.address.text = ''
self.ids.name.text = ''
self.ids.info.clear_widgets()
self.on_pre_enter() # refresh screen
def delete_email(self, check):
address = check.ids.who_name.text
del self.email[address]
self.ids.info.remove_widget(check)
self.saveEmails()
##########################################################
########### PRE ENTER ####################################
def on_pre_enter(self):
self.ids.info.clear_widgets()
self.loadEmails()
try:
for name, mail in self.email.items():
self.ids.info.add_widget(Checkboxes(name=name, mail=mail, email=self.email))
except ValueError:
print('VALUE ERROR: Label.text accept only "str"')
self.ids.pess_date.text = strftime('[b]%A[/b], %B %Y') # time and date
##########################################################
########### PRE LEAVE ####################################
def on_pre_leave(self):
self.ids.info.clear_widgets()
self.saveEmails()
class Checkboxes(BoxLayout):
def __init__(self, name='', mail='', email='', **kwargs):
super().__init__(**kwargs)
self.ids.who_name.text = name
self.ids.who_email.text = mail
def on_checkbox_Active(self, checkboxInstance, isActive):
address = ''
if isActive:
'''
Email is used for recipient
'''
name = self.ids.who_name.text
email = self.ids.who_email.text
print('Email Set!')
return email
else:
'''
Nothing happens, email is not used
'''
##########################################################
######## TRACKERS WINDOWS ################################
##########################################################
class Trackers(Screen):
email = {'davi': 'example#gmail.com'}
storage = {}
pess_storage = {}
path = ''
def on_pre_enter(self):
self.path = App.get_running_app().user_data_dir + '/'
self.loadData()
for tracker, num in self.storage.items():
self.ids.track.add_widget(Tracker(text=tracker, number=num))
def on_pre_leave(self):
self.ids.track.clear_widgets()
self.saveData()
def saveData(self, *args):
with open(self.path + 'data.json', 'w') as data:
json.dump(self.storage, data)
def loadData(self, *args):
try:
with open(self.path + 'data.json', 'r') as data:
self.storage = json.load(data)
print(self.storage)
except FileNotFoundError:
pass
def savePESS(self, PESS):
self.pess_storage['physical'] = PESS.ids.phy_text.text
self.pess_storage['emotional'] = PESS.ids.emo_text.text
self.pess_storage['spiritual'] = PESS.ids.spi_text.text
self.pess_storage['sexual'] = PESS.ids.sex_text.text
self.pess_storage['comment'] = PESS.ids.comment.text
def save_text(self, tracker, text_input, *args):
tracker.ids.label.text = text_input.text
self.storage[text_input.text] = '0'
self.saveData()
self.loadData()
print('testing')
def send(self, PESS):
self.path = App.get_running_app().user_data_dir + '/'
with open(self.path + 'bat', 'r') as bat:
login = bat.read()
davi = self.email['davi']
mail = PESS.ids.who_email.text
#kevin = self.email['kevin'] # instead of this I'd like to have this variable linked to
gmail = GMail(davi, login)
day = strftime("%a, %b %d, %Y")
tracker_message = 'PESS\n'
subject_message = f"Subject: PESS {day}"
for pess, txt in self.pess_storage.items():
tracker_message += f"\t{pess.title()}: {txt}\n"
for tracker, numbers in self.storage.items():
tracker_message += f"\n{numbers} ---> {tracker}\n"
message = f"{subject_message}\n\n{tracker_message}"
msg = Message(f'PESS | {day}', to=mail, text=message)
gmail.send(msg)
self.sent_confirmation(f'{self.ids.who_name.text}: {mail}')
def sent_confirmation(self, recipient):
box = BoxLayout(orientation='vertical', padding=40, spacing=5)
pop = Popup(title='Email Sent', content=box, size_hint=(None,None), size=(self.width, self.width/2))
info = Label(text=f'Congrats, {recipient} has recieved an email.')
box.add_widget(info)
pop.open()
self.saveData()
class Tracker(BoxLayout):
def __init__(self, text='', number='', **kwargs):
super().__init__(**kwargs)
self.ids.label.text = text
self.ids.count_add.text = number
class Pess(App):
def build(self):
Config.set('graphics', 'width', '600')
Config.set('graphics', 'height', '800')
from kivy.core.window import Window
Window.clearcolor = get_color_from_hex('#262829')
return ScreenGenerator()
if __name__ == '__main__':
Pess().run()
kv file
#: import rgba kivy.utils.get_color_from_hex
#: import CheckBox kivy.uix.checkbox
<Label>:
font_size: '17dp'
<MenuButton#ButtonBehavior+Label>:
canvas.before:
Color:
rgba: 0.1, 0.5, 0.7, 1
Ellipse:
pos: self.pos
size: self.height, self.height
Ellipse:
pos: self.x + self.width - self.height, self.y
size: self.height, self.height
Rectangle:
pos: self.x + self.height / 2, self.y
size: self.width - self.height, self.height
<RoundButton#ButtonBehavior+Label>:
canvas.before:
Color:
rgba: 0.8, 0.3, 0.1, 1
Ellipse:
pos: self.width / 2.265, self.y + 130
size: self.height - self.height / 1.5, self.height / 3
<MenuButton2#ButtonBehavior+Label>:
canvas.before:
Color:
rgba: 0.8, 0.3, 0.1, 1
Ellipse:
pos: self.pos
size: self.height, self.height
Ellipse:
pos: self.x + self.width - self.height, self.y
size: self.height, self.height
Rectangle:
pos: self.x + self.height / 2, self.y
size: self.width - self.height, self.height
<FloatButton#ButtonBehavior+FloatLayout>:
id: float_root
size_hint: (None, None)
text: '[b]+[/b]'
font_size: '48dp'
btn_size: (140,140)
size: (140,140)
bg_color: (0.8, 0.3, 0.1, 1)
pos_hint: {'x': 5.4, 'y': .17}
Button:
text: float_root.text
font_size: '14dp'
#allow_stretch: True
markup: True
size_hint: (None, None)
size: float_root.btn_size
pos_hint: float_root.pos_hint
background_normal: ''
background_color: (0,1,0,0)
canvas.before:
Color:
rgba: float_root.bg_color
Ellipse:
pos: self.pos
size: self.size
<TrackerButton#Button>:
background_color: 0,0,0,0
<ScreenGenerator>:
Menu:
name: 'menu'
Trackers:
name: 'track'
PessQuestions:
name: 'pess'
<Menu>:
BoxLayout:
orientation: 'vertical'
padding: 20
spacing: 30
Image:
source: 'book.png'
allow_strech: True
Label:
canvas.before:
Color:
rgba: (1,1,1,.7)
Rectangle:
size: self.size
pos: self.pos
size_hint_y: None
height: 1
MenuButton:
text: 'Enter Trackers'
height: dp(60)
size_hint_y: None
background_image: ''
background_color: rgba('#637075')
on_release: app.root.current = 'track'
MenuButton:
text: 'Enter PESS'
height: dp(60)
size_hint_y: None
background_image: ''
background_color: rgba('#637075')
on_release: app.root.current = 'pess'
Label:
canvas.before:
Color:
rgba: (1,1,1,.7)
Rectangle:
size: self.size
pos: self.pos
size_hint_y: None
height: 1
Label:
id: time
text: ''
markup: True
<PessQuestions>:
BoxLayout:
orientation: 'vertical'
pos_hint: {'top': 1}
ActionBar:
height: self.minimum_height + dp(50)
size_hint_y: None
background_image: ''
background_color: rgba('#ffffff') # rgba('#0B3242')
ActionView:
ActionPrevious:
title: '[b]PESS[/b]'
font_size: '17dp'
color: rgba('#AFB7BA')
markup: True
on_release: app.root.current = 'track'
ActionButton:
text: 'SEND'
color: rgba('#AFB7BA')
on_release: app.root.get_screen('track').send(root) # if .send() function is on another class outside of 'class PessQuestions' use the .get_screen() to locate the right screen class
#on_release: app.root.send()
ActionButton:
text: 'TRACKER'
color: rgba('#AFB7BA')
on_release: app.root.current = 'track'
ActionButton:
text: 'HOME'
color: rgba('#AFB7BA')
on_release: app.root.current = 'menu'
BoxLayout:
orientation: 'vertical'
padding: dp(10)
spacing: dp(12)
pos_hint: {'top': 1}
TextInput:
id: phy_text
hint_text: 'Physical'
size_hint_y: None
height: self.minimum_height + dp(7)
multiline: False
TextInput:
id: emo_text
hint_text: 'Emotional'
size_hint_y: None
height: self.minimum_height + dp(7)
multiline: False
TextInput:
id: spi_text
hint_text: 'Spiritual'
size_hint_y: None
height: self.minimum_height + dp(7)
multiline: False
TextInput:
id: sex_text
hint_text: 'Sexual'
size_hint_y: None
height: self.minimum_height + dp(7)
multiline: False
TextInput:
id: comment
hint_text: 'Leave a comment'
size_hint_y: None
height: self.minimum_height + dp(100)
MenuButton:
id: save_pess
text: 'Save PESS'
height: dp(60)
size_hint_y: None
background_image: ''
on_press: self.text = 'SAVED!'
on_release: app.root.get_screen('track').savePESS(root)
MenuButton2:
text: 'Clear PESS'
height: dp(60)
size_hint_y: None
background_image: ''
on_press: root.ids.save_pess.text = 'Save PESS'
on_release: root.resetPESS()
MenuButton:
text: 'Send Report'
color: rgba('#AFB7BA')
height: dp(60)
size_hint_y: None
background_image: ''
on_release: app.root.get_screen('track').send(root) # if .send() function is on another class outside of 'class PessQuestions' use the .get_screen() to locate the right screen class
#on_release: app.root.send()
Label:
canvas.before:
Color:
rgba: (1,1,1,.7)
Rectangle:
size: self.size
pos: self.pos
size_hint_y: None
height: 1
Label:
text: '[b]Physical, Emotional, Spiritual, Sexual[/b] | These principles when lived with a full purpose of heart will invite the Holy Ghost into your lives.'
markup: True
text_size: self.width, None
size_hint: 1, None
height: self.texture_size[1]
Label:
id: pess_date
text: ''
markup: True
Label:
canvas.before:
Color:
rgba: (1,1,1,.7)
Rectangle:
size: self.size
pos: self.pos
size_hint_y: None
height: 1
# Label & Checkbox creation | for selecting email address
Label:
text: "EMAIL"
text_size: self.width, None
size_hint: 1, None
height: self.texture_size[1]
ScrollView:
BoxLayout:
id: info
orientation: 'vertical'
padding: dp(5)
spacing: dp(7)
#size_hint_y: None
#height: self.minimum_height + dp(50)
TextInput:
id: name
hint_text: 'Name'
size_hint_y: None
height: self.minimum_height + dp(7)
multiline: False
TextInput:
id: address
hint_text: 'Email Address'
size_hint_y: None
height: self.minimum_height + dp(7)
multiline: False
MenuButton:
id: save_email
text: 'Save Email'
height: dp(60)
size_hint_y: None
background_image: ''
on_release: root.saveEmails()
<Checkboxes>:
CheckBox:
group: 'emails'
color: .294, .761, .623
on_active: root.on_checkbox_Active(self, self.active)
#on_active: app.root.get_screen('pess').on_checkbox_Active(self, self.active)
size_hint_x: .50
Label:
id: who_name
text: ''
text_size: self.width, None
halign: 'left'
Label:
id: who_email
text: ''
text_size: self.width, None
halign: 'left'
Button:
text: '[b]X[/b]'
markup: True
size_hint_x: None
width: dp(20)
on_release: app.root.get_screen('pess').delete_email(root)
<Trackers>:
BoxLayout:
orientation: 'vertical'
ActionBar:
height: self.minimum_height + dp(50)
size_hint_y: None
background_image: ''
background_color: rgba('#ffffff') #rgba('#0B3242')
ActionView:
ActionPrevious:
title: '[b]TRACKERS[/b]'
font_size: '17dp'
color: rgba('#AFB7BA')
markup: True
on_release: app.root.current = 'pess'
ActionButton:
text: 'RESET'
color: rgba('#AFB7BA')
on_release: root.reset_pop()
ActionButton:
text: 'PESS'
color: rgba('#AFB7BA')
on_release: app.root.current = 'pess'
ActionButton:
text: 'HOME'
color: rgba('#AFB7BA')
on_release: app.root.current = 'menu'
ScrollView:
BoxLayout:
id: track
orientation: 'vertical'
padding: dp(10)
spacing: dp(15)
size_hint_y: None
height: self.minimum_height
BoxLayout:
size_hint_y: None
height: dp(100)
Button:
text: '+'
font_size: '56dp'
size_hint_y: None
background_image: ''
background_color: (0,0,0,0)
on_release: root.addWidget()
#BoxLayout:
#FloatButton:
# pos_hint_x: None
# pos_hint_y: None
# on_release: root.addWidget()
<Tracker>:
count_add: count_add
name: name
size_hint_y: None
height: 130
canvas.before:
Color:
rgba: 0.1, 0.5, 0.7, 1
Rectangle:
pos: self.pos[0] + self.height/2, self.pos[1]
size: self.size[0] - self.height, self.height
Ellipse:
pos: self.pos[0], self.pos[1]
size: self.height, self.height
Ellipse:
pos: self.pos[0] + self.width - self.height, self.pos[1]
size: self.height, self.height
TrackerButton:
text: '[b]X[/b]'
markup: True
size_hint_x: None
width: 120
on_release: app.root.get_screen('track').delete_storage(root)
Label:
id: name
canvas.before:
Color:
rgba: (1,1,1,.7)
Rectangle:
size: self.size
pos: self.pos
size_hint_x: None
width: 1
TrackerButton:
id: label
font_size: '16dp'
on_release: app.root.get_screen('track').change_name(root)
TrackerButton:
id: count_add
font_size: '16dp'
text: '0'
size_hint_x: None
width: 120
on_release: app.root.get_screen('track').add_num(root)
Label:
canvas.before:
Color:
rgba: (1,1,1,.7)
Rectangle:
size: self.size
pos: self.pos
size_hint_x: None
width: 1
TrackerButton:
text: '[b]-[/b]'
font_size: '24dp'
markup: True
size_hint_x: None
width: 120
on_release: app.root.get_screen('track').subtract_num(root)
I had my code running really well, but all of the email sending information was hardcoded. I wanted to give the user options to input an email address and send it to that address.
I added the class Checkboxes which get's created every time I add a name and email address and hit the "Save Email" It's grouped so they are radio buttons.
I can't seem to connect the email address to my send function on the class Trackers... I hope all of this makes some sense. I might be overly complicating things for myself. I could use some help please. Thank you.
Just came across this question and since I am short on time I wont be able to help you completely. If you ever want to access widgets inside and outside of your class screens you need to have a shared parent for the both of them. In your main py file you can have something like this defined.
class MainInterface(BoxLayout):
def __init__(self, **kwargs):
super(MainInterface, self).__init__(**kwargs)
class WindowManager(ScreenManager):
pass
class HomeWindow(Screen):
...
class TrackerWindow(Screen):
...
sm = WindowManager()
screens = [HomeWindow(name="Home"), TrackerWindow(name="TrackerWindow")]
for screen in screens:
sm.add_widget(screen)
class MyMainApp(App):
def build(self):
root = MainInterface()
return root
The way you use your kv file from now on will be different from what you are used to. Your kv file can look something like this. I'll be using different example uses for one button to save time for myself.
<MainInterface>:
WindowManager:
id: screenmanager
HomeWindow:
id: homewindow
...
Button:
pos_hint:{"x":0,"top":1}
size_hint: 0.125, 0.1
text: "Some Stuff"
font_size: (root.width**1 + root.height**1) / 10**2
on_release:
root.ids['trackerwindow'].send(YourData)
root.ids['homewindow'].access_user_inputs(self.parent.user_inputs)
root.ids['screenmanager'].transition.direction = "left"
root.ids['screenmanager'].current="TrackerWindow"
TrackerWindow:
id: trackerwindow
...
notice how on the homescreen button to get information from its own screen you can't just use root.access_user_inputs(root.user_inputs) you created a parent tree so you use self.parent if you want to access a function from your windowmanager you would do a similar set up but use self.parent.parent. I hope this helps and if you have questions please ask and I'll be able to further help you later.

Kivy: Buttons in GridLayout have gap

Inside of GridLayout, odd numbered Button children do not appear.
I've tried several configurations of both Button and GridLayout size, size_hint, height, etc, and cant seem to fix this. Removing the Button class from the children fixes this, but I'd like the functionality of a button widget.
main.py:
from kivy.app import App
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.gridlayout import GridLayout
from kivy.properties import NumericProperty, StringProperty, ListProperty
from kivy.uix.behaviors.focus import FocusBehavior
from kivy.uix.button import Button
class Tube(Button, RelativeLayout, FocusBehavior):
pass
class TubeMapView(GridLayout, FocusBehavior):
orderNumber = NumericProperty()
customerName = StringProperty("")
tubeList = ListProperty([])
bundleList = ListProperty([])
def add_tube(self):
self.tubeList.append(Tube())
self.add_widget(self.tubeList[-1])
def _on_focusable(self, instance, value):
self.add_tube()
def keyboard_on_key_down(self, window, keycode, text, modifiers):
print(keycode)
if keycode[1] is 'enter':
self.add_tube()
class LengthView(GridLayout):
pass
class AppView(GridLayout):
pass
class TubeMapApp(App):
pass
if __name__ == '__main__':
TubeMapApp().run()
tubemap.kv:
<Tube>:
size_hint_y: None
height: dp(60)
canvas.before:
Color:
rgba: (0,1,0,1)
Rectangle:
size: self.size
<LengthView>:
size_hint_x: 1
size_hint_y: 1
canvas.before:
Color:
rgba: (0,0,1,1)
Rectangle:
size: self.size
<TubeMapView>:
cols: 1
rows: None
size_hint_max_x:
size_hint_y: None
height: self.minimum_height
canvas.before:
Color:
rgba: (0,1,0,1)
Rectangle:
pos: self.pos
size: self.size
AppView:
cols: 2
rows: None
RelativeLayout:
size_hint_x: 0.75
ScrollView:
size: self.size
TubeMapView:
focus: True
Tube:
Tube:
Tube:
RelativeLayout:
size_hint_x: 0.25
ScrollView:
LengthView:
I would expect each one to render, but instead only every other Button renders, starting with the first one:
You can inherit from Button, RelativeLayout and FocusBehavior, and create your own style.
Snippets - py file
class Tube(Button, RelativeLayout, FocusBehavior):
pass
Snippets - kv fie
<-Tube>:
text: ''
focus: False
size_hint_y: None
height: dp(60)
canvas.before:
Color:
rgba: (0,1,0,1)
# rgba: (1,0,1,0.5) if self.focus else (0,1,0,1)
Rectangle:
size: self.size
state_image: self.background_normal if self.state == 'normal' else self.background_down
disabled_image: self.background_disabled_normal if self.state == 'normal' else self.background_disabled_down
canvas:
Color:
rgba: (1,0,1,1) if self.focus else self.background_color
BorderImage:
border: self.border
pos: self.pos
size: self.size
source: self.disabled_image if self.disabled else self.state_image
Color:
rgba: 1, 1, 1, 1
Rectangle:
texture: self.texture
size: self.texture_size
pos: int(self.center_x - self.texture_size[0] / 2.), int(self.center_y - self.texture_size[1] / 2.)
Output
Example
The following kv file is a mock-up.
poc.kv
<-Tube>:
text: ''
focus: False
size_hint_y: None
height: dp(60)
canvas.before:
Color:
rgba: (0,1,0,1)
Rectangle:
size: self.size
state_image: self.background_normal if self.state == 'normal' else self.background_down
disabled_image: self.background_disabled_normal if self.state == 'normal' else self.background_disabled_down
canvas:
Color:
rgba: (1,0,1,1) if self.focus else self.background_color
BorderImage:
border: self.border
pos: self.pos
size: self.size
source: self.disabled_image if self.disabled else self.state_image
Color:
rgba: 1, 1, 1, 1
Rectangle:
texture: self.texture
size: self.texture_size
pos: int(self.center_x - self.texture_size[0] / 2.), int(self.center_y - self.texture_size[1] / 2.)
<LengthView>:
size_hint_x: 1
size_hint_y: 1
canvas.before:
Color:
rgba: (0,0,1,1)
Rectangle:
size: self.size
<TubeMapView>:
cols: 1
rows: None
size_hint_y: None
height: self.minimum_height
canvas.before:
Color:
rgba: (0,1,0,1)
Rectangle:
pos: self.pos
size: self.size
AppView:
cols: 2
rows: None
RelativeLayout:
size_hint_x: 0.75
ScrollView:
size: self.size
TubeMapView:
Tube:
focus: True
text: 'tube 1'
Tube:
text: 'tube 2'
Tube:
text: 'tube 3'
RelativeLayout:
size_hint_x: 0.25
ScrollView:
LengthView:
If you want your Tube to be a RelativeLayout that behaves like a Button, change the declaration of your Tube class to:
class Tube(ButtonBehavior, FocusBehavior, RelativeLayout):
pass
Note that the documentation says Behavior class must precede the Widget class in inheritance.
This change does what I think you want.

Kivy how to remove label and add

I want to make a simple game where you tap and you earn money. I made some code which does that however I don't know how to remove the label. Right now all it does is add 1 to the money variable and make new label.
.py
money = 0
class GameScreen(Screen):
def money(self):
global money
money += 1
self.add_widget(Label(text=str(money), color=(1,0,0,1), font_size=(45),size_hint=(0.2,0.1), pos_hint={"center_x":0.5, "center_y":0.9}))
print(money)
.kv
<GameScreen>:
name: "GameScreen"
canvas:
Color:
rgb: 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
Button:
size: self.texture_size
on_release: root.money()
text: "Press"
font_size: 50
color: 1,1,1,1
background_color: (0,0,0,1)
background_normal: ""
background_down: ""
size_hint: None, None
pos_hint: {"center_x":0.5, "center_y":0.6}
width: self.texture_size[0] + dp(10)
height: self.texture_size[1] + dp(10)
Removing a Label to place a widget with another text consumes recourses in an unavoidable way, you only have to update the text. So you must add the label the first time and then update the text. On the other hand it is recommended that the name of variables, classes and functions are not the same. And try to avoid using global variables because they are difficult to debug.
Making those changes we obtain the following code:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.uix.screenmanager import Screen
class GameScreen(Screen):
def __init__(self, **args):
Screen.__init__(self, **args)
self.money = 0
self.label = Label(text=str(self.money), color=(1,0,0,1), font_size=(45),size_hint=(0.2,0.1), pos_hint={"center_x":0.5, "center_y":0.9})
self.add_widget(self.label)
def add_money(self):
self.money += 1
self.label.text = str(self.money)
Builder.load_string('''
<GameScreen>:
name: "GameScreen"
canvas:
Color:
rgb: 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
Button:
size: self.texture_size
on_release: root.add_money()
text: "Press"
font_size: 50
color: 1,1,1,1
background_color: (0,0,0,1)
background_normal: ""
background_down: ""
size_hint: None, None
pos_hint: {"center_x":0.5, "center_y":0.6}
width: self.texture_size[0] + dp(10)
height: self.texture_size[1] + dp(10)
''')
class TestApp(App):
def build(self):
return GameScreen()
if __name__ == '__main__':
TestApp().run()

Categories