How to use button behaviour inside of scrollview in kivy? - python

I am trying to figure out how I could make a label have the properties of a button, while the label itself is scrollable.
I have tried a couple of different things but haven't managed to get it to work, here's my current code, my end goal is to have every number as a separate "clickable" entity, but for now if I could figure out how to make the whole lable have the properties of a button, that would be good enough.
My code:
import kivy
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty
from kivy.clock import Clock
from kivy.properties import ListProperty
from kivy.properties import StringProperty
from kivy.uix.scrollview import ScrollView
from kivy.uix.button import ButtonBehavior
from kivy.uix.label import Label
class Testime(Widget):
pass
class loendtest(App):
tulemus = NumericProperty()
loend = ListProperty()
loend2 = StringProperty()
loend3 = StringProperty()
def build(self):
return Testime()
if __name__ == "__main__":
loendtest().run()
<Testime>:
GridLayout:
cols:3
size: root.size
Button:
text: "add a result"
on_press:
app.tulemus += 1
app.loend.append(app.tulemus)
print(app.tulemus)
print(app.loend)
app.loend2 = " " + str(app.loend).strip('[]').replace(',', '\n')
print(app.loend2.split())
app.loend3 = " " + str(app.loend2.split()).strip('[]').replace(',', '\n')
print(app.loend3)
ScrollView:
Label:
size_hint_y: 2
font_size: 75
text_size: None, self.height
valign: "top"
text:
app.loend3

Just create a custom Label that acts like a Button:
class MyButtonLabel(ButtonBehavior, Label):
pass
... and replace your Label with it...
OR, you can do that on the kv side, like this:
<MyButtonLabel#ButtonBehavior+Label>

Related

How to use slider as progress bar and volume control in kivy python using kv file not main python file

I want to create slider by file kv Not with the main Python file I was trying to program the code but it didn't turn out like I expected.
file py
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.scrollview import ScrollView
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.core.window import Window
from kivy.base import Builder
from kivy.core.spelling import Spelling
from kivy.core.audio import SoundLoader
from kivy.animation import Animation
class ManagImage(Screen):
s=SoundLoader.load("mm.mp3")
a=s.play()
lang=s.length
sl=s.get_pos()
def release(self,va):
self.sl = self.s.get_pos()
self.s.seek(int(va))
self.s.play()
self.slide.text=str((format((va/60),".2f")))
self.ids.lb.font_size=int(100)
class slider(App):
def build(self):
self.title = "slider"
slider().run()
File Kv
ManagImage:
slide:lb
BoxLayout:
orientation: "vertical"
padding:10
spacing:10
size:root.size
pos:root.pos
Label:
id : lb
Slider:
id : sd
pos_hint:{"right":1}
min: 0
max: root.lang
step: 1
value:root.sl
value_track:True
value_track_color:(150/255,60/255/10/255,1)
orientation: "horizontal"
on_value:root.release(self.value)
You can accomplish that by scheduling a method that fetches the audio position of the sound at specific intervals. Here is a modified version of your code that does that:
from kivy.app import App
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.properties import NumericProperty
from kivy.uix.screenmanager import Screen
from kivy.core.audio import SoundLoader
kv = '''
ManagImage:
slide:lb
BoxLayout:
orientation: "vertical"
padding:10
spacing:10
size:root.size
pos:root.pos
Label:
id : lb
Slider:
id : sd
pos_hint:{"right":1}
min: 0
max: root.lang
step: 1
value:root.sl
value_track:True
value_track_color:(150/255,60/255/10/255,1)
orientation: "horizontal"
# on_value:root.release(self.value) # not needed and causes an infinite loop
'''
class ManagImage(Screen):
sl = NumericProperty(0)
lang = NumericProperty(0)
def __init__(self, **kwargs):
super(ManagImage, self).__init__(**kwargs)
# start the sound playing
self.s = SoundLoader.load("test.mp3")
self.s.play()
self.lang = self.s.length
# schedule a method to update the self.sl every half second
self.sched = Clock.schedule_interval(self.get_audio_pos, 0.5)
def get_audio_pos(self, dt):
self.sl = self.s.get_pos()
class slider(App):
def build(self):
self.title = "slider"
return Builder.load_string(kv)
slider().run()
The get_audio_pos() method updates the sl property regularly and the Slider automatically updates since the kv sets its value to that Property.
The release() method was removed (along with its mention in kv) since it is not needed and will cause an infinite loop.
I have included the kv as a string in my code just for my own convenience. It can be used in a separate kv file just as well.

How can I print a list of data each in its own label underneath each other

I have a large list of data that I want to display on my app, but I having trouble finding a way to print the data in a vertical matter, each list element in its own label underneath the last. In the future I wish to replace the labels with MDCard.
Also if the list reaches the bottom of the screen, how will I be able to scroll down?
*.py
import kivy
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.properties import StringProperty
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder
from kivymd.app import MDApp
from kivy.uix.screenmanager import ScreenManager, Screen
class FirstWindow(Screen):
def __init__(self, **kwargs):
super(FirstWindow, self).__init__(**kwargs)
list1 = ['1','2','3','4','5','6','7','8','9','10','11','12']
for x in list1:
self.add_widget(Label(text=x,pos_hint={'center_x':0.5, 'center_y':0.5}))
class WindowManager(ScreenManager):
pass
kv = Builder.load_file('NearMe.kv')
class NearMeApp(App):
def build(self):
return kv
if __name__ == '__main__':
NearMeApp().run()
*.kv
WindowManager:
FirstWindow:
<FirstWindow>:
name:"FirstWindow"
GridLayout:
cols:1
size: root.width, root.height
GridLayout:
cols:3
Your __init__() method of FirstWindow is adding all the Labels to the FirstWindow, but they are all at the same position. I suspect that you actually want to add the Labels to the innermost GridLayout. To do that, you can add an id to that GridLayout in the kv:
WindowManager:
FirstWindow:
<FirstWindow>:
name:"FirstWindow"
GridLayout:
cols:1
size: root.width, root.height
GridLayout:
id: grid # Added id
cols:3
Then refactor your FirstWindow class to use that id:
class FirstWindow(Screen):
def __init__(self, **kwargs):
super(FirstWindow, self).__init__(**kwargs)
Clock.schedule_once(self.fill) # this must be delayed until the `id` is available
def fill(self, dt):
grid = self.ids.grid # get a reference to the GridLayout
list1 = ['1','2','3','4','5','6','7','8','9','10','11','12']
for x in list1:
grid.add_widget(Label(text=x,pos_hint={'center_x':0.5, 'center_y':0.5})) # add Labels to the GridLayout

I want to generate random words as labels. i tried so many thing and it wouldn't work

by clicking correct button I want to generate random words from text document word list as labels. in python kivy. Here are my codes below:
import kivy
import random
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.image import Image
from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.lang.builder import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition
from kivy.uix.slider import Slider
from kivy.uix.pagelayout import PageLayout
from kivy.properties import ObjectProperty, NumericProperty, StringProperty
class Begin1After(FloatLayout):
count = 0
my_text = StringProperty("0")
def check_off(self):
self.count += 1
self.my_text = str(self.count)
def incorrect_off(self):
self.count -= 1
self.my_text = str(self.count)
class MyApp(App):
pass
myapp = MyApp()
myapp.run()
And here is my kivy code:
<Begin1After>:
Label:
text: root.my_text
pos_hint: {'x': .03, 'y': .35}
font_size: 20
bold: True
Label:
text: "Team One:"
bold: True
pos_hint: {'x': -.05, 'y': .35}
font_size: 20
Button:
size_hint: .06, .08
pos_hint: {'x': .65, 'y': .1}
background_color: 0, 0, 0, 0
on_release: root.check_off()
Button:
size_hint: .06, .08
pos_hint: {'x': .3, 'y': .1}
background_color: 0, 0, 0, 0
on_release: root.incorrect_off()
Problem: focus.
What do you want ?
"I want to generate random words as labels. i tried so many thing and it wouldn't work"
Ok, that's the general idea but concretly, what is the next step you want to do ? What is the technical problematic that is blocking you right now ?
By looking at your code, I understand that you want to use a kivy App.
create an App: done
display the app ? Fail
So I can give you this answer:
import kivy
from kivy.app import App
from kivy.uix.label import Label
# Replace this with your
# current version
kivy.require('1.11.1')
# Defining a class
class MyFirstKivyApp(App):
# Function that returns
# the root widget
def build(self):
# Label with text Hello World is
# returned as root widget
return Label(text ="Hello World !")
# Here our class is initialized
# and its run() method is called.
# This initializes and starts
# our Kivy application.
MyFirstKivyApp().run()
from https://www.geeksforgeeks.org/hello-world-in-kivy/
So now, based on this working code. What is the next step you want to do ?
Display 2 buttons and 2 labels ? go on and ask for help if you have a precise error to give.
Good luck ! :)

Black screen on kivy how to fix

when I try to run the code it just displays a blank screen I tried to find answers everywhere but nothing works
This is my main.py file:
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.graphics import *
from kivy.lang import *
from kivy.uix.screenmanager import *
class MyWidgets(Widget):
pass
kv = Builder.load_file('math.kv')
class Calculator(App):
def build(self):
return kv
if __name__ == '__main__':
Calculator().run()
And this is my math.kv file:
<MyWidgets>
num: num
GridLayout:
cols: 1
TextInput:
id: num
multiline: False
GridLayout:
cols: 3
Button:
text: '1'
font_size: 25
Button:
text: '2'
font_size: 25
Button:
text: '3'
font_size: 25
Looks like you have an indent error in build function. Still, that should have shown some error instead of showing a blank screen. Then in your .kv file, I don't know what that num is. After removing num from .kv and correcting indentation error I run the file and it works fine.
Here's the code I used:
.py
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.graphics import *
from kivy.lang import *
from kivy.uix.screenmanager import *
class MyWidgets(Widget):
pass
class Calculator(App):
def build(self):
kv = Builder.load_file('math.kv')
return kv
if __name__ == '__main__':
Calculator().run()
.kv
<MyWidgets>
GridLayout:
cols: 1
TextInput:
id: num
multiline: False
GridLayout:
cols: 3
Button:
text: '1'
font_size: 25
Button:
text: '2'
font_size: 25
Button:
text: '3'
font_size: 25

I can't scroll my page

How to add my widget in a ScrollView or ListView to scroll it?
I've written a code but it doesn't work good, this is my main.py:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.scrollview import ScrollView
from random import random
class chat_history(BoxLayout):
def profile(self):
return random(),random(),random()
Builder.load_file('widg.kv')
class myApp(App ):
def build(self):
x=BoxLayout(orientation='vertical')
s=ScrollView()
for i in range(1,21):
x.add_widget(chat_history(height=50))
s.add_widget(x)
return s
myApp().run()
And this is my kv file:
<chat_history>:
height:100
BoxLayout:
height:50
name:'haha very funny '
size_hint_y:None
id:cv
orientation:'horizontal'
canvas:
Color:
rgb:root.profile()
Ellipse:
pos:root.pos
Label:
text_hint:{'x':0,'y':0.1}
pos:root.pos
size_hint_x:0.7
height:cv.height
text:cv.name
id:lbl
First of all, you should prevent the layout from automatically adapting its height to the height of its parent widget (size_hint_y = None).
On the other hand, make sure the height is such that there is something to scroll. You must explicitly specify layout height.
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.scrollview import ScrollView
from random import random
kv_text = '''
<chat_history>:
size_hint_y: None
height:100
BoxLayout:
height:50
name:'haha very funny '
size_hint_y:None
id:cv
orientation:'horizontal'
canvas:
Color:
rgb:root.profile()
Ellipse:
pos:root.pos
Label:
text_hint:{'x':0,'y':0.1}
pos:root.pos
size_hint_x:0.7
height:cv.height
text:cv.name
id:lbl
'''
class chat_history(BoxLayout):
def profile(self):
return random(),random(),random()
class myApp(App ):
def build(self):
Builder.load_string(kv_text)
x=BoxLayout(orientation='vertical', size_hint_y=None) #<<<<<<<<<<<
x.bind(minimum_height=x.setter('height')) #<<<<<<<<<<<
s=ScrollView()
for i in range(1,21):
x.add_widget(chat_history(height=50))
s.add_widget(x)
return s
myApp().run()

Categories

Resources