I'd like to write a roundish menu with Kivy. At the end it should somehow look like this:
I've stumbled upon some problems at the early beginnings. I already created the "mainmenu"-button (0.1). Now I wanted to create 2 new menu-circles 2.1 + 2.2. The problem is that the events for the two new buttons occur when I click on the main-button but nothing happens by clicking on the new buttons.
I really appreciate any help. :)
menu.py
import kivy
kivy.require('1.8.0') # replace with your current kivy version !
from kivy.app import App
from kivy.uix.label import Label
from kivy.factory import Factory
from kivy.uix.scatter import Scatter
from kivy.uix.widget import Widget
from kivy.uix.floatlayout import FloatLayout
from kivy.lang import Builder
class menuApp(App):
print "test"
def secTouch(self):
print "sectouch"
class RootWidget(FloatLayout):
pass
class Menu (FloatLayout):
def newMenu(self):
dynamicMenu = Factory.First()
self.add_widget(dynamicMenu)
pass
class First(Scatter):
def firstTouch(self):
dynamicWidget = Factory.Second()
self.add_widget(dynamicWidget)
print "touch"
pass
if __name__ == '__main__':
menuApp().run()
menu.kv
#:kivy 1.8.0
#: set buttonSize 100, 100
#: set middleOfScreen 0,0
RootWidget:
<RootWidget>:
Menu
<Menu>
on_touch_down: root.newMenu()
<First>:
id: first
pos: root.size[0]/2-self.size[0]/2, root.size[1]/2-self.size[1]/2
size: 100, 100
size_hint: None, None
Widget:
on_touch_down: root.firstTouch()
id: me
size_hint: None, None
size: 100, 100
pos: root.size[0]/2-self.size[0]/2, root.size[1]/2-self.size[1]/2
canvas:
Color:
rgb: 1, 0, 0
Ellipse:
pos: me.pos
size: buttonSize
<Second#Scatter>:
pos: root.size[0]/2-self.size[0]/2+40, root.size[1]/2-self.size[1]/2+40
size: 100, 100
size_hint: None, None
on_touch_down: app.secTouch()
canvas:
Color:
rgb: 1, 0, 0
Ellipse:
pos: root.size[0]/2-self.size[0]/2+40, root.size[1]/2-self.size[1]/2+40
size: buttonSize
Every touch event is dispatched to the on_touch_down event handlers, not just touches in a given area (within the widget). Each time you touch the screen, regardless of where, the Menus on_touch_down is fired. You should use collide_point() to ensure the touch is within the given boundaries.
The Grabbing Touch Events section of the Kivy guide has an example of collide_point(), as well as some more info about touch events in general.
But, the basic idea:
def on_touch_down(self, touch):
if self.collide_point(*touch.pos):
# do stuff here
return True # 'handle' the event so it will not propagate
Related
I'm making an app in python kivy and in my tacscreen I have a draggable Image and an Label, whenever I drag my draggable Image my label drags with it as well. The position of the label is just below the draggable Image. The problem that I'm facing is whenever I resize my window and drag the image the label goes from this to this the space between the Image and the label is too much. How can I fix this? I want the label to always be like how it is in the first screenshot even after I resize the screen and drag. Below is my code. I have been trying to find a solution to this for a months now. I really appreciate any help. Thanks!
main.py
from kivy.properties import BooleanProperty
from kivy.properties import ObjectProperty
from kivy.metrics import dp
from kivy.app import App
from kivy.uix.screenmanager import Screen
from kivy.lang import Builder
from kivy.uix.behaviors import DragBehavior
from kivy.uix.image import Image
class DragImage1(DragBehavior, Image):
dragging = BooleanProperty(False)
drag_label = ObjectProperty()
def on_touch_move(self, touch):
if touch.grab_current is self:
self.drag_label.pos = self.x, self.y - dp(300)
return super().on_touch_move(touch)
def on_touch_up(self, touch):
uid = self._get_uid()
if uid in touch.ud:
# do something on drop
print(self.source, 'dropped at', touch.x, touch.y)
return super(DragImage1, self).on_touch_up(touch)
class TacScreen(Screen):
Pass
GUI = Builder.load_file("main.kv")
class MainApp(App):
def build(self):
return GUI
def change_screen(self, screen_name, *args):
self.root.current = screen_name
MainApp().run()
main.kv
#:include tacscreen.kv
ScreenManager:
id: screen_manager
TacScreen:
name: "tac_screen"
id: tac_screen
tacscreen.kv
<tacscreen>:
#:import utils kivy.utils
canvas.before:
Rectangle:
pos: self.pos
size: self.size
source: "Background.png"
DragImage1:
drag_label: per
pos: root.center_x - self.width/2, root.center_y - self.height/0.3
size_hint: 1, .1
source: "Image.png"
Label:
id: per
text: "Hello"
font_size: "20dp"
pos: root.center_x - self.width/2, root.center_y - self.height/1.2
You can modify your kv to do the positioning for you:
DragImage1:
id: di # added id for use by the Label
drag_label: per
pos: root.center_x - self.width/2, root.center_y - self.height/0.3
size_hint: 1, .1
source: "Image.png"
Label:
id: per
text: "Hello"
font_size: "20dp"
size_hint: None, None
size: self.texture_size # set size to just contain the text
pos: di.center_x - self.width/2, di.y - self.height # adjust postion based on the DragImage1
And, since kv is now handling the positioning, you should remove the on_touch_move() method from the DragImage1 class.
Note that this will handle positioning when resizing before dragging. But if you drag before resizing, then the resizing will revert the position to that defined in the kv.
I am developing an app using Kivy for Android and IOS, i haven't tried it on any mobile yet but i have been noticing that i need to add some sort off 'touch' events so the buttons, swipes and etc will work on a mobile touchscreen.
i've tried searching around for examples but i didn't exactly get the concept, and i was wondering what exactly do i need to do for it to be ready for touch events, i am thinking of making a 'swiping touch' to move between pages on both sides, what do i need to do to make this happen?
When you want to swipe through pages as you have mentioned. It could be a nice option to use PageLayout. Check the docs:https://kivy.org/doc/stable/api-kivy.uix.pagelayout.html
PageLayout is where you have several pages and you can swipe through them. It could be suitable for you.
Here is a very simple example.Where you will have three pages
PageLayout:
Button:
text: 'page1'
Button:
text: 'page2'
Button:
text: 'page3'
Here is a advanced pagelayout example from kv file. The pagelyout then consists of floatlayouts. But you could use other layouts too
<Example>:
PageLayout:
FloatLayout:
id: string1
canvas:
Color:
rgb:utils.get_color_from_hex("#2BFFFA")
Rectangle:
size: self.size
pos:self.pos
Image:
size_hint:.9,1
pos_hint:{"top": 1,"right": 1}
source: "string/str1.png"
FloatLayout:
canvas:
Color:
rgb:utils.get_color_from_hex("#39FF22")
Rectangle:
size: self.size
pos:self.pos
Image:
size_hint:.9,1
pos_hint:{"top": 1,"right": 1}
source: "string/str1_sol.png"
FloatLayout:
canvas:
Color:
rgb:utils.get_color_from_hex("#2BFFFA")
Rectangle:
size: self.size
pos:self.pos
Image:
size_hint:.9,1
pos_hint:{"top": 1,"right": 1}
source: "string/str2.png"
Notice that my main layout is a pagelayout and in the floatlayout I have floatlayouts. So now I have three pages to swipe through
Or you could use a screemanger to manage your screens. . And then you just have to click on a button and then you will automatically switch screens. Here is a example. This is better than pagelayouts.
import kivy
from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.properties import ObjectProperty
class ScreenOne(Screen):
def __init__ (self,**kwargs):
super (ScreenOne, self).__init__(**kwargs)
my_box1 = BoxLayout(orientation='vertical')
my_label1 = Label(text="BlaBlaBla on screen 1", font_size='24dp')
my_button1 = Button(text="Go to screen 2",size_hint_y=None, size_y=100)
my_button1.bind(on_press=self.changer)
my_box1.add_widget(my_label1)
my_box1.add_widget(my_button1)
self.add_widget(my_box1)
def changer(self,*args):
self.manager.current = 'screen2'
class ScreenTwo(Screen):
def __init__(self,**kwargs):
super (ScreenTwo,self).__init__(**kwargs)
my_box1 = BoxLayout(orientation='vertical')
my_label1 = Label(text="BlaBlaBla on screen 2",font_size='24dp')
my_button1 = Button(text="Go to screen 1",size_hint_y=None, size_y=100)
my_button1.bind(on_press=self.changer)
my_box1.add_widget(my_label1)
my_box1.add_widget(my_button1)
self.add_widget(my_box1)
def changer(self,*args):
self.manager.current = 'screen1'
class TestApp(App):
def build(self):
my_screenmanager = ScreenManager()
screen1 = ScreenOne(name='screen1')
screen2 = ScreenTwo(name='screen2')
my_screenmanager.add_widget(screen1)
my_screenmanager.add_widget(screen2)
return my_screenmanager
if __name__ == '__main__':
TestApp().run()
I am trying to create a simple attendance app.
When program is launched all labels are in deselected list
Expected behavior: when any label is selected data moves to the selected list and now selected labels are in the end of the joined list. Then RecycleView refreshes to display this change.
So I managed to make the data to move from one list to another, but I can't make RecycleView to refresh
I tried using ids but failed
I hope someone can help me. I think this is a routine problem for people who are knowledgeable, but for noobs like me it is not.
I am asking question on this site for the first time so sorry in advance
here is the code:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.recycleview import RecycleView
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.label import Label
from kivy.properties import BooleanProperty
from kivy.properties import ListProperty
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from datetime import datetime
import kivy
from kivy.config import Config
Config.set('graphics', 'width', '300')
Config.set('graphics', 'height', '500')
importedlist = ['Novella Varela', 'Caroll Faircloth', 'Douglas Schissler',
'Rolande Hassell', 'Hayley Rivero', 'Niesha Dungy', 'Winfred Dejonge', 'Venetta Milum']
deselected_list = importedlist[:]
selected_list = []
class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior,
RecycleBoxLayout):
''' Adds selection and focus behaviour to the view. '''
class SelectableLabel(RecycleDataViewBehavior, Label):
''' Add selection support to the Label '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableLabel, self).refresh_view_attrs(
rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableLabel, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view.
and add/remove items from lists
'''
self.selected = is_selected
if self.selected and self.text in deselected_list:
selected_list.append(self.text)
deselected_list.remove(self.text)
print(selected_list)
elif not self.selected and self.text in selected_list:
deselected_list.append(self.text)
selected_list.remove(self.text)
print(deselected_list)
class RV(RecycleView):
# this needs to be updated every time any label is selected or deselected
def __init__(self, **kwargs):
super(RV, self).__init__(**kwargs)
self.data = ([{'text': str(row)} for row in sorted(deselected_list)]
+ [{'text': str(row)} for row in sorted(selected_list)])
class Screen(BoxLayout):
now = datetime.now()
def nowdate(self):
return self.now.strftime('%d')
def nowmonth(self):
return self.now.strftime('%m')
def nowyear(self):
return self.now.strftime('%y')
def nowhour(self):
return self.now.strftime('%H')
def nowminute(self):
return self.now.strftime('%M')
Builder.load_string('''
#:import datetime datetime
<Screen>:
orientation: 'vertical'
BoxLayout:
size_hint_y: None
height: 30
TextInput:
id: date
text: root.nowdate()
TextInput:
id: date
text: root.nowmonth()
TextInput:
id: date
text: root.nowyear()
TextInput:
id: date
text: root.nowhour()
TextInput:
id: date
text: root.nowminute()
Button:
RV:
viewclass: 'SelectableLabel'
SelectableRecycleBoxLayout:
default_size: None, dp(45)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
multiselect: True
touch_multiselect: True
Button:
size_hint_y: None
height: 30
<SelectableLabel>:
# Draw a background to indicate selection
canvas.before:
Color:
rgba: (.0, 0.9, .1, .3) if self.selected else (0, 0, 0, 1)
Rectangle:
pos: self.pos
size: self.size
''')
class TestApp(App):
def build(self):
return Screen()
if __name__ == '__main__':
TestApp().run()
Alright, so I did actually stumble a few times trying to sort this out but I think I've got it. What I did was create two recycle views and a CustomLabel that has access to ButtonBehaviors so you can use 'on_press' instead of 'on_touch_down' (which propagates through the entire tree rather than the interacted with element).
Example Video
The py file:
from kivy.app import App
from kivy.uix.recycleview import RecycleView
from kivy.uix.label import Label
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.floatlayout import FloatLayout
# Create a Custom ButtonLabel that can use on_press
class ButtonLabel(ButtonBehavior, Label):
# App.get_running_app() lets us traverse all the way through our app from
# the very top, which allows us access to any id. In this case we are accessing
# the content of our selected_list_view of our app
#property
def selected_list_content(self):
return App.get_running_app().root.ids.selected_list.ids.content
# And in this case, we're accessing the content of our deselected_list_view
#property
def deselected_list_content(self):
return App.get_running_app().root.ids.deselected_list.ids.content
# This is our callback that our Label's will call when pressed
def change_location(self):
# If the label's parent is equal* the selected list, we remove the label from its
# parent, and then we add it to the other list
if self.parent == self.selected_list_content:
self.parent.remove_widget(self)
self.deselected_list_content.add_widget(self)
# If the label's parent is not the selected list, then it is the deselected list
# so we remove it from its parent and add it to the selected list
else:
self.parent.remove_widget(self)
self.selected_list_content.add_widget(self)
#* Note: Kivy uses weak references. This is why we use ==, and not 'is'
# We create a CustomRecycleView that we will define in our kv file
class CustomRecycleView(RecycleView):
pass
class MainWindow(FloatLayout):
pass
class ExampleApp(App):
def build(self):
# We create an instance of the MainWindow class, so we can access its id
# to import our list. Otherwise we would have nothing to add the list too
main_window = MainWindow()
importedlist = ['Novella Varela', 'Caroll Faircloth', 'Douglas Schissler',
'Rolande Hassell', 'Hayley Rivero', 'Niesha Dungy', 'Winfred Dejonge', 'Venetta Milum']
# We create a Label for each Name in our imported list, and then add it
# to the content of selected list as a default
# I'm sure you'll be importing our own lists in a different manner
# This is just for the example
for name in importedlist:
NameLabel = ButtonLabel(text=(name))
main_window.ids.selected_list.ids.content.add_widget(NameLabel)
return main_window
if __name__ == '__main__':
ExampleApp().run()
The kv file:
#:kivy 1.10.0
# We create a reference to the ButtonLabel class in our py file
<ButtonLabel>:
# We add our callback to our ButtonLabels on press event, on_press
on_press: root.change_location()
# We create a reference to our CustomRecycleView class in our py file
<CustomRecycleView>:
# We create a GridLayout to store all of the content in our RecycleView
GridLayout:
# We give it the id content so we can define the two property values in
# ButtonLabel class in the py file
id: content
size_hint_y: None
# One column because we want it to be vertical list list
cols: 1
# This set up, as well as size_hint_y set to None
# is so we can scroll vertically without issue
row_default_height: 60
height: self.minimum_height
<MainWindow>:
# We then create two instances of our CustomRecycleView, give them the ids
# referenced by the ButtonLabel methods as well as give them equal share of the
# screen space so they do not step on each others toes
# The canvas here is just for prototyping purposes to make sure they are the
# properly defined sizes. You can do whatever with them you would like tbh.
CustomRecycleView:
id: selected_list
size_hint: 1, .5
pos_hint: {'x': 0, 'y': .5}
canvas:
Color:
rgba: 100, 0, 0, .2
Rectangle:
size: self.size
pos: self.pos
CustomRecycleView:
id: deselected_list
size_hint: 1, .45
canvas:
Color:
rgba: 0, 0, 100, .2
Rectangle:
size: self.size
pos: self.pos
As far as I am aware, kv language is useful when making a static display, e.g. not when making game which need much widget's positioning during runtime. Here I try to make a simple game, but still need much positioning, so kv language is out of context for the widget, but not for the screen. I use screen to differentiate the main menu and game screen. But when I try to use 'add_widget' to insert my image, it always positioned at the middle of the window. Later I found out that the screen size is only 100x100.
Below are the only way that I can thought of, but still with no luck:
class HomeScreen(Screen):
pass
class GameScreen(Screen):
pass
class ScreenManagement(ScreenManager):
pass
presentation=Builder.load_file('ProjectSD.kv')
class ProjectSDApp(App):
def build(self):
A=presentation
A.screens[0].size=(Window.size)
A.screens[0].add_widget(Label(text='hello',font_Size=80,pos=(0,0)))
return A
if __name__=='__main__':
print(Window.size)
ProjectSDApp().run()
and my ProjectSD.kv file:
#: import FadeTransition kivy.uix.screenmanager.FadeTransition
ScreenManagement:
transition: FadeTransition()
HomeScreen:
GameScreen:
<Button>:
font_name:'attackofthecucumbers.ttf'
<HomeScreen>:
name:'home'
canvas:
Rectangle:
pos: self.pos
size: self.size
source: 'nature.jpg'
Label:
text: 'Monopoly GX'
font_name:'KBDunkTank.ttf'
font_size:100
size_hint:0.7,0.2
pos:root.width*0.15,root.height*0.70
Button:
on_release: app.root.current = "game"
text: 'Play Game'
font_size:root.width/20
size_hint:0.3,0.15
pos:root.width*0.35,root.height*0.45
Button:
on_release: app.stop()
text: 'exit'
font_size:root.width/20
size_hint:0.3,0.15
pos:root.width*0.35,root.height*0.20
<GameScreen>:
name:'game'
Button:
on_release: app.root.current = "home"
background_color: (1,0.15,0.2,0.8)
text: 'X'
font_size:root.width/40
size_hint:0.05,0.05
pos:root.width*0.95,root.height*0.95
Since there is no 'pos' method in screen object, I put my widget to position (0,0) manually.
The only way I found is just below:
https://kivyspacegame.wordpress.com/2014/08/10/tutorial-flappy-ship-part-2-build-simple-menus-and-animate-your-games-using-clock/
So my question is, if I use screen object from kivy's build in, how to achieve the same result? So I can still adding and remove widget as I want it later?
I'm not entirely clear on what you're asking; I don't see anywhere in your code where you are trying to add an Image to a Layout. You add a label to the middle and that works fine.
I think because you are creating screens without any layouts and not setting a default window size, that the screens just take up their minimum default size. You need to add a layout and fill it with stuff that has a defined size, or set a window size at the beginning e.g:
# window import
from kivy.core.window import Window
from kivy.utils import get_color_from_hex
Window.size = (1920/2,1080/2)
Window.clearcolor = get_color_from_hex('#000000') # black
Here is some code that creates your two Screens, and adds a draggable and a static Image at a position to a FloatLayout.
from kivy.app import App
from kivy.uix.screenmanager import (ScreenManager, Screen)
from kivy.uix.image import Image
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.behaviors import DragBehavior
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
class HomeScreen(Screen):
pass
class GameScreen(Screen):
pass
class ScreenManagement(ScreenManager):
pass
class MovingImage(DragBehavior,Image):
pass
class DragLabel(DragBehavior, Label):
pass
class StaticImage(Image):
pass
class MyApp(App):
def build(self):
A = ScreenManagement()
A.current = 'game'
A.screens[1].ids.gamefloat.add_widget(MovingImage(size_hint = [0.3,0.3]))
A.screens[1].ids.gamefloat.add_widget(StaticImage(pos = (150,300)))
return A
if __name__=='__main__':
MyApp().run()
and the .kv file called myapp.kv
<ScreenManagement>:
HomeScreen:
GameScreen:
<Button>:
<HomeScreen>:
name:'home'
canvas:
Rectangle:
pos: self.pos
size: self.size
source: 'image.jpg'
Label:
text: 'Monopoly GX'
font_size:100
size_hint:0.7,0.2
pos:root.width*0.15,root.height*0.70
Button:
on_release: app.root.current = "game"
text: 'Play Game'
font_size:root.width/20
size_hint:0.3,0.15
pos:root.width*0.35,root.height*0.45
Button:
on_release: app.stop()
text: 'exit'
font_size:root.width/20
size_hint:0.3,0.15
pos:root.width*0.35,root.height*0.20
<GameScreen>:
name:'game'
FloatLayout:
id: gamefloat
Button:
on_release: app.root.current = "home"
background_color: (1,0.15,0.2,0.8)
text: 'X'
font_size:root.width/40
size_hint:0.05,0.05
pos:root.width*0.95,root.height*0.95
<MovingImage>:
drag_rectangle: self.x, self.y, self.width, self.height
drag_timeout: 1000000
drag_distance: 0
source: 'image.jpg'
<StaticImage>:
source: 'image.jpg'
I add widgets to a GridLayout in a ScrollView, so its content expands dynamically.
By default, without user scrolling, the view stays at the top, no matter how many more widgets do you add. If the user scrolls, the view attaches to this point, but it seems a little annoying for me to have to scroll down (even a little bit) for the view to always show the latest content. How can I make it show the downmost part by default?
Here is the sample code just in case:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.uix.gridlayout import GridLayout
Builder.load_string('''
<MessageView>:
canvas:
Color:
rgba: 1, 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
<Message>:
canvas:
Color:
rgba: 0, 1, 0, 0.3
Rectangle:
pos: self.pos
size: self.size
''')
class Message(Widget):
pass
class MessageView(ScrollView):
pass
class TestApp(App):
def msg_in(self, btn):
msg = Message()
msg.size_hint = [None, None]
self.msg_layout.add_widget(msg)
def build(self):
self.scr = Screen()
self.sv1_main = MessageView(pos_hint={"top": 0.87, "center_x": 0.5},
size_hint=(0.97, 0.65))
self.msg_layout = GridLayout(cols=1,
size_hint_y=None)
self.msg_layout.bind(minimum_height=self.msg_layout.setter('height'))
self.bt1_main = Button(size_hint=(0.1, 0.078),
pos_hint={"top": 0.097, "center_x": 0.927},
on_press=self.msg_in)
self.scr.add_widget(self.sv1_main)
self.sv1_main.add_widget(self.msg_layout)
self.scr.add_widget(self.bt1_main)
return self.scr
TestApp().run()
You can use scroll_to method after adding a new content.
class TestApp(App):
def msg_in(self, btn):
msg = Message()
msg.size_hint = [None, None]
self.msg_layout.add_widget(msg)
self.sv1_main.scroll_to(msg)
# ...