Kivy/python : How to check checkbox from a .py file - python

I have written some code in Python (test.py) and kivy (test.kv).
When I run test.py then male checkbox shows checked and female checkbox unchecked because I am using in test.kv file:
active: root.male
But I want the same thing from a .py file. How to checked male checkbox from a .py file?
test.py
from kivy.uix.screenmanager import Screen
from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.properties import ObjectProperty
Window.size = (600, 325)
class UserGroup(Screen):
male = ObjectProperty(None)
female = ObjectProperty(None)
age = ObjectProperty(None)
def insert_data(self):
print('')
class FactUserGroup(App):
def build(self):
self.root = Builder.load_file('test.kv')
return self.root
if __name__ == '__main__':
FactUserGroup().run()
test.kv
<CustomLabel#Label>:
text_size: self.size
valign: "middle"
padding_x: 5
<SingleLineTextInput#TextInput>:
multiline: False
<GreenButton#Button>:
background_color: 1, 1, 1, 1
size_hint_y: None
height: self.parent.height * 0.120
UserGroup
male: chk_male
female: chk_female
GridLayout:
cols: 2
padding : 30,30
spacing: 20, 20
row_default_height: '30dp'
Label:
text: 'Male'
text_size: self.size
valign: 'middle'
CheckBox:
group: 'check'
id : chk_male
active: root.male
Label:
text: 'Female'
text_size: self.size
valign: 'middle'
CheckBox:
group: 'check'
id: chk_female
GreenButton:
text: 'Ok'
GreenButton:
text: 'Cancel'
on_press: app.stop()
Can someone help me?

The solution is to use BooleanProperty, and add active: root.female. In the example it illustrates when the Kivy app is running the checkbox for female is active (Figure 1), after 5 seconds, it will automatically switch to the checkbox for male (Figure 2) using Clock.schedule_once.
test.py
from kivy.properties import ObjectProperty, BooleanProperty
...
class UserGroup(Screen):
male = BooleanProperty(False)
female = BooleanProperty(True)
test.kv
CheckBox:
group: 'check'
id: chk_female
active: root.female
Example
test.py
from kivy.uix.screenmanager import Screen
from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.properties import ObjectProperty, BooleanProperty
from kivy.clock import Clock
Window.size = (600, 325)
class UserGroup(Screen):
male = BooleanProperty(False)
female = BooleanProperty(True)
age = ObjectProperty(None)
def __init__(self, **kwargs):
super(UserGroup, self).__init__(**kwargs)
Clock.schedule_once(self.switch_checkbox, 5)
def switch_checkbox(self, dt):
self.female = False
self.male = True
def insert_data(self):
print('')
class FactUserGroup(App):
def build(self):
self.root = Builder.load_file('test.kv')
return self.root
if __name__ == '__main__':
FactUserGroup().run()
test.kv
#:kivy 1.10.0
<CustomLabel#Label>:
text_size: self.size
valign: "middle"
padding_x: 5
<SingleLineTextInput#TextInput>:
multiline: False
<GreenButton#Button>:
background_color: 1, 1, 1, 1
size_hint_y: None
height: self.parent.height * 0.120
UserGroup:
GridLayout:
cols: 2
padding : 30,30
spacing: 20, 20
row_default_height: '30dp'
Label:
text: 'Male'
text_size: self.size
valign: 'middle'
CheckBox:
group: 'check'
id : chk_male
active: root.male
Label:
text: 'Female'
text_size: self.size
valign: 'middle'
CheckBox:
group: 'check'
id: chk_female
active: root.female
GreenButton:
text: 'Ok'
GreenButton:
text: 'Cancel'
on_press: app.stop()
Output

Related

How do I have a checkbox enable/disable a button using Kivy?

If the checkbox is checked, I want the button to be enabled. If it isn't checked, I want it to be disabled. I thought that is what my disable_button function does by checking if the checkbox is checked if self.ids.checkbox_confirm.active == False: and then disabling the button with self.ids.submit_button.disabled == True. But, the latter statement isn't doing anything.
main.py
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.core.window import Window
from kivy.properties import ObjectProperty
class MainWindow(Screen):
def on_pre_enter(self):
Window.size=(750,400)
def checkbox_click(self, instance, value):
return value
def disable_button(self):
print(self.ids.checkbox_confirm.active)
if self.ids.checkbox_confirm.active == False:
self.ids.submit_button.disabled == True
else:
self.ids.submit_button.disabled == False
class SecondWindow(Screen):
def on_pre_enter(self):
Window.fullscreen='auto'
pass
class WindowManager(ScreenManager):
pass
class MyMainApp(App):
def build(self):
Window.clearcolor = (1,1,1,1)
return kv
kv = Builder.load_file("my.kv")
if __name__ == "__main__":
MyMainApp().run()
.kv file
WindowManager:
MainWindow:
SecondWindow:
<MainWindow>:
name: "main"
BoxLayout:
orientation: "vertical"
size: root.width, root.height
padding: 50
Label:
text: "Email"
color: 0,0,0,1
font_size: 32
BoxLayout:
orientation: "horizontal"
Label:
text: "Email Address:"
color: 0,0,0,1
TextInput:
size_hint_y: None
pos_hint: {'center_y': .5}
height: 38
multiline: True
padding: 10
BoxLayout:
orientation: "horizontal"
Label:
text: "I double-checked that my email is typed correctly:"
color: 0,0,0,1
CheckBox:
id: checkbox_confirm
on_active:
root.checkbox_click(self, self.active)
root.disable_button()
pos_hint: {'center_x': .5}
BoxLayout
orientation: "vertical"
Button:
id:submit_button
text: "Submit"
size_hint: (0.2, None)
pos_hint: {'center_x': .5}
height: 50
on_release:
app.root.current = "second"
root.manager.transition.direction = "left"
<SecondWindow>:
name: "second"
I didn't test it but you have typo in code.
To assign new value you have to use = instead of ==
if self.ids.checkbox_confirm.active == False:
self.ids.submit_button.disabled = True # need `=` instead of `==`
else:
self.ids.submit_button.disabled = False # need `=` instead of `==`
BTW:
You can write it in single line using not
self.ids.submit_button.disabled = not self.ids.checkbox_confirm.active

Hello everyone, how do i play video in kivy at screen manager i tried but couldn't

imports:
from kivy.lang import Builder
from kivy.uix.textinput import TextInput
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import StringProperty
from kivy.properties import ObjectProperty
from kivy.uix.label import Label
from kivy.core.window import Window
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.video import Video
kv = '''
<V>
BoxLayout:
spacing: 10
padding: 20
orientation: "vertical"
width: root.width,root.height
Button:
text: " [Login-Screen] "
background_color: (1,1,1,1)
color: (1,0,0,1)
bold: True
font_size: 17
size_hint: (None,None)
width: 200
height: 50
on_release:
root.manager.current = "Login"
root.manager.transition.direction = "up"
<Login>
ben: benName.text
pw: passwort.text
knopf: btn
knopff: btnn
GridLayout:
cols: 1
size: root.width,root.height
GridLayout:
cols: 2
Label:
text: "Username"
font_size: 25
TextInput:
id: benName
multiline: False
font_size: 30
Label:
text: "Password"
font_size: 25
bold: True
TextInput:
password: True
id: passwort
multiline: False
font_size: 40
Button:
size_hint: (1.,1.10)
text:" Start "
id: btn
font_size: 40
on_release:
Button:
size_hint: (1.,1.10)
text: " Exit "
id: btnn
font_size: 40
on_release: app.stop()
'''
MyApp class:
class Login(Screen):
ben = StringProperty()
pw = StringProperty()
knopf = ObjectProperty()
class MyApp(App):
Builder.load_string(kv)
def build(self):
ms = ScreenManager()
ms.add_widget(V(name='V'))
ms.add_widget(Login(name='login'))
self.title = "MyApp"
return ms
class V(Screen):
def logo(self):
video = Video(source='loding_4K.mp4')
video.state='play'
video.options = {'eos': 'loop'}
video.allow_stretch=True
return video
if __name__ == '__main__':
MyApp().run()
Your are not calling logo() method. This is how you can do it in the kv file which is easier.
from kivy.lang import Builder
from kivy.uix.textinput import TextInput
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import StringProperty
from kivy.properties import ObjectProperty
from kivy.uix.label import Label
from kivy.core.window import Window
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.video import Video
kv = '''
<V>
BoxLayout:
spacing: 10
padding: 20
orientation: "vertical"
width: root.width,root.height
Video:
source: "loding_4K.mp4"
state: "play"
options: {'eos': 'loop'}
allow_stretch: True
Button:
text: " [Login-Screen] "
background_color: (1,1,1,1)
color: (1,0,0,1)
bold: True
font_size: 17
size_hint: (None,None)
width: 200
height: 50
on_release:
root.manager.current = "Login"
root.manager.transition.direction = "up"
<Login>
ben: benName.text
pw: passwort.text
knopf: btn
knopff: btnn
GridLayout:
cols: 1
size: root.width,root.height
GridLayout:
cols: 2
Label:
text: "Username"
font_size: 25
TextInput:
id: benName
multiline: False
font_size: 30
Label:
text: "Password"
font_size: 25
bold: True
TextInput:
password: True
id: passwort
multiline: False
font_size: 40
Button:
size_hint: (1.,1.10)
text:" Start "
id: btn
font_size: 40
on_release:
Button:
size_hint: (1.,1.10)
text: " Exit "
id: btnn
font_size: 40
on_release: app.stop()
'''
class Login(Screen):
ben = StringProperty()
pw = StringProperty()
knopf = ObjectProperty()
class MyApp(App):
Builder.load_string(kv)
def build(self):
ms = ScreenManager()
ms.add_widget(V(name='V'))
ms.add_widget(Login(name='login'))
self.title = "MyApp"
return ms
class V(Screen):
pass
if __name__ == '__main__':
MyApp().run()

Python : How add a datepicker in .kv file

Can anyone tell me how to add a date picker or kivy calendar on date TextBox?
I have two file test.py and test.kv file.
test.py
import kivy
import sqlite3 as lite
from kivy.uix.screenmanager import Screen
from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.label import Label
Window.clearcolor = (0.5, 0.5, 0.5, 1)
Window.size = (400, 125)
class Testing(Screen):
pass
class Testing(App):
def build(self):
self.root = Builder.load_file('test.kv')
return self.root
if __name__ == '__main__':
Testing().run()
test.kv
Testing:
BoxLayout:
orientation: "vertical"
padding : 20, 20
BoxLayout:
orientation: "horizontal"
padding: 10, 10
spacing: 10, 10
size_hint_x: .55
Label:
text: "Date"
text_size: self.size
valign: 'middle'
size_hint_x: .2
TextInput:
size_hint_x: .3
BoxLayout:
orientation: "horizontal"
padding : 10, 0
spacing: 10, 10
size_hint: .5, .7
pos_hint: {'x': .25, 'y':.25}
Button:
text: 'Ok'
on_release:
root.dismiss()
Button:
text: 'Cancel'
on_release: root.dismiss()
.kv file
#:import MDTextField kivymd.uix.textfield.MDTextField
MDTextField:
id: set_date
hint_text: 'Start Date'
write_tab: False
on_focus: root.setDate()
.py file
from kivymd.uix.picker import MDDatePicker
def setDate(self,dobj):
self.ids.set_date.text = str(dobj)
pass
def fromDate(self):
self.foc = self.ids.set_date.focus
if(self.foc==True):
MDDatePicker(self.setFDate).open()
else:
print("not")

Python : How to get value of dynmaic row

I am new to python and kivy.
I am trying to get value of dynamic row.But now i am getting value like this
Column2
Column1
Can someone tell me how to get value like this ?
1,column1,column2
2,column1,column2
Because i have three column in my database table like id,name,value and i want to insert value in database table through loop
I am using this code
def insert_value(self):
values = []
rows = self.ids.rows
for row in reversed(rows.children):
for ch in row.children:
if isinstance(ch, TextInput):
values.append(ch.text)
lenArray = len(values)
for x in range(0, lenArray):
print (values[x])
demo.py
from kivy.uix.screenmanager import Screen
from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BooleanProperty, ListProperty, StringProperty, ObjectProperty, NumericProperty
from kivy.uix.textinput import TextInput
Window.size = (450, 525)
class display(Screen):
def add_more(self):
self.ids.rows.add_row()
def insert_value(self):
values = []
rows = self.ids.rows
for row in reversed(rows.children):
for ch in row.children:
if isinstance(ch, TextInput):
values.append(ch.text)
lenArray = len(values)
for x in range(0, lenArray):
print (values[x])
class Row(BoxLayout):
button_text = StringProperty("")
id = ObjectProperty(None)
class Rows(BoxLayout):
orientation = "vertical"
row_count = 0
def __init__(self, **kwargs):
super(Rows, self).__init__(**kwargs)
self.add_row()
def add_row(self):
self.row_count += 1
self.add_widget(Row(button_text=str(self.row_count),id=str("test"+str(self.row_count))))
class test(App):
def build(self):
self.root = Builder.load_file('demo.kv')
return self.root
if __name__ == '__main__':
test().run()
demo.kv
<Row>:
orientation: "horizontal"
spacing: 0, 5
Button:
text: root.button_text
size_hint_x: .2
TextInput:
text:"Column1"
size_hint_x: .8
TextInput:
text:"Column2"
size_hint_x: .8
display:
BoxLayout:
orientation: "vertical"
padding : 20, 20
BoxLayout:
orientation: "horizontal"
Button:
size_hint_x: .2
text: "+Add More"
valign: 'bottom'
on_press: root.add_more()
BoxLayout:
orientation: "horizontal"
Label:
size_hint_x: .2
text: "SN"
valign: 'bottom'
Label:
size_hint_x: .8
text: "Value"
valign: 'bottom'
Rows:
id: rows
BoxLayout:
orientation: "horizontal"
padding : 10, 0
spacing: 10, 10
size_hint: .5, .7
pos_hint: {'x': .25, 'y':.25}
Button:
text: 'Ok'
on_release:
root.insert_value()
Button:
text: 'Cancel'
on_release: root.dismiss()
To maintain a structure we must create a list of lists, then in each list the first parameter is the text of the Button that we filter through isinstance(), and the other elements are concatenated.
[...]
from kivy.uix.button import Button
class display(Screen):
def add_more(self):
self.ids.rows.add_row()
def insert_value(self):
values = []
rows = self.ids.rows
for row in reversed(rows.children):
vals = []
for ch in reversed(row.children):
if isinstance(ch, TextInput):
vals.append(ch.text)
if isinstance(ch, Button):
vals.insert(0, ch.text)
values.append(vals)
for val in values:
print("{},{},{}".format(*val))
[...]
One option is to add a ListProperty to your Row class that stores the values of the row in the order you want, which makes it easier to obtain them later.
You can use a ListView to show the rows.
Demo.kv:
<Row>:
values: row_id.text, col1.text, col2.text
orientation: "horizontal"
spacing: 0, 5
size_hint_y: None
height: 30
Button:
id: row_id
text: root.button_text
size_hint_x: .2
TextInput:
id: col1
text:"Column1"
size_hint_x: .8
TextInput:
id: col2
text:"Column2"
size_hint_x: .8
<Rows>:
content: content
BoxLayout:
id: content
orientation: "vertical"
size_hint_y: None
height: self.minimum_height
Display:
rows: rows
BoxLayout:
orientation: "vertical"
padding : 20, 20
BoxLayout:
orientation: "horizontal"
Button:
size_hint_x: .2
text: "+Add More"
valign: 'bottom'
on_press: root.add_more()
BoxLayout:
orientation: "horizontal"
Label:
size_hint_x: .2
text: "SN"
valign: 'bottom'
Label:
size_hint_x: .8
text: "Value"
valign: 'bottom'
Rows:
id: rows
BoxLayout:
orientation: "horizontal"
padding : 10, 10
spacing: 10, 10
size_hint: .5, .7
pos_hint: {'x': .25, 'y':.25}
Button:
text: 'Ok'
on_release:
root.insert_value()
Button:
text: 'Cancel'
on_release: root.dismiss()
Demo.py:
from kivy.uix.screenmanager import Screen
from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ListProperty, StringProperty, ObjectProperty
from kivy.uix.scrollview import ScrollView
from kivy.clock import Clock
Window.size = (450, 525)
class Display(Screen):
rows = ObjectProperty(None)
def __init__(self, **kwargs):
super(Display, self).__init__(**kwargs)
def add_more(self):
self.rows.add_row()
def insert_value(self):
values = [row.values for row in reversed(self.rows.content.children)]
for row in values:
print(row)
class Row(BoxLayout):
button_text = StringProperty("")
id = ObjectProperty(None)
values = ListProperty()
class Rows(ScrollView):
row_count = 0
content = ObjectProperty(None)
def __init__(self, **kwargs):
super(Rows, self).__init__(**kwargs)
Clock.schedule_once(self.add_row)
def add_row(self, *args):
self.row_count += 1
self.content.add_widget(Row(button_text=str(self.row_count),
id="test" + str(self.row_count)))
class Test(App):
def build(self):
self.root = Builder.load_file('Demo.kv')
return self.root
if __name__ == '__main__':
Test().run()

how to close a Screen without interrupting the program in Kivy

I am beginner with respect to programming already resorted to previously forum which received help for simple issues.
I am currently looking for a way to close a screen without interrupting my program, I am using the "thread" to continue executing commands while the program is in the loop.
MAIN
from kivy.app import App
from kivy.uix.screenmanager import Screen
from kivy.properties import ObjectProperty
from kivy.core.audio import SoundLoader
from time import sleep
import thread
class Display(Screen):
myslider = ObjectProperty(None)
def get_number(self):
occupancy = format(self.myslider.value)
print "value = ",occupancy
def display_screen():
thread.start_new_thread(myApp().run, ())
def remove_screen():
Screen.disabled()
def ring():
sound = SoundLoader.load('ring.wav')
if sound:
sound.play()
class myApp(App):
def build(self):
return Display()
if __name__ == '__main__':
ring()
sleep(2)
display_screen()
sleep(7)
remove_screen()
KV file
#:import random random.random
<Display>:
orientation: 'vertical'
myslider: slider
canvas:
Color:
rgb: 1, 1, 1
Rectangle:
source: 'data/images/background.jpg'
size: self.size
BoxLayout:
padding: 10
spacing: 10
size_hint: 1, None
pos_hint: {'top': 1}
height: 44
Image:
size_hint: None, None
size: 24, 24
source: 'data/logo/kivy-icon-24.png'
Label:
height: 24
text_size: self.size
color: (1, 1, 1, .8)
text: 'Kivy 1.9.0.'
valign: 'middle'
GridLayout:
cols: 2
Label:
text: 'Please enter \nthe number of occupants?'
bold: True
font_name: 'data/fonts/DejaVuSans.ttf'
font_size: 22
halign: 'center'
Slider:
id: slider
min: 0.0
max: 15.0
value: 1.0
step: 1.0
orientation: "horizontal"
width: "38dp"
Label
text: ''
Label
text: '{}'.format(slider.value)
halign: 'center'
valign: 'top'
bold: True
text_size: self.size
font_size: 18
Button:
text: 'Enter'
size_hint_y: None
height: '50sp'
on_release: root.get_number()
I left remove_screen function because it was what I found so far in my research. but not work.

Categories