I'm stuck trying to position widgets in kivy in a FloatLayout using pos_hint.
If the label exists from the beginning, e.g. if I can define the pos_hint in the .kv file, everything works as expected. However, I'm trying to create buttons later on. Using this .kv file (named layouttest.kv):
<NewButton#Button>:
size_hint: (0.1, 0.1)
<BasicFloatLayout#FloatLayout>:
Button:
size_hint: (0.4, 0.2)
pos_hint: {'x': 0.0, 'top': 1.0}
text: 'create Button'
on_release: self.parent.create_Button()
and this python code, I am trying to position newly created blank buttons at a random y-position ranging from 0%-100% of the size of my BasicFloatLayout, and at a random x-position ranging from 0-200px.
If I press the button once, everything behaves as expected. On a second press, the first created button will change its y-position such that it is identical with the newly created button. On a third press, both old buttons will align with the newly created button and so on. The x-positioning will however remain as expected. Can someone please explain what I'm doing wrong here?
(Bonus points if you can help me moving the buttons using the update function and pos_hint)
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.properties import NumericProperty
from kivy.clock import Clock
import random
class BasicFloatLayout(FloatLayout):
timer = NumericProperty(0)
def update(self, *args):
self.timer += 1
for child in self.children:
try: child.update()
except AttributeError:
pass
def create_Button(self):
button = NewButton( (random.random(), random.random()) )
self.add_widget(button)
class NewButton(Button):
def __init__(self, pos, **kwargs):
super(NewButton, self).__init__(**kwargs)
self.pos[0] = 200*pos[0]
self.pos_hint['y'] = pos[1]
class layouttestApp(App):
def build(self):
GUI = BasicFloatLayout()
Clock.schedule_interval(GUI.update, 1/30.)
return GUI
if __name__ == "__main__":
layouttestApp().run()
First, make pos_hint: {'x': 0.0, 'y': 0.5}(because it's hard to get 2 different things work, if you are using x, use y instead of Top, if you are using Top, then use Bottom insead of x)
Second, instead of giving on_release: self.parent.create_Button() in the kv file, do this: on_release: root.create_Button()
Third, you have only assigned for the y value , you should also assign for the x value, the line is self.pos_hint['y'] = pos[1] inside the NewButton class.
But you can make it more simple by doing this:
#from your first class......
def create_Button(self):
button = NewButton(self.pos_hint{'x' : random.random(), 'y' : random.random()}
self.add_widget(button)
class NewButton(Button):
def __init__(self, *kwargs):
pass
Hope this makes some kind of sense, and you can modify it more.
(Note: I haven't wrote the begining part of your main class, I am lazy ;-p)
Related
In the following code, there are problems (1) and (2) according to the title.
If kvLang is used as described in this code, the figure (blue ellipse) will be drawn to the expected Cell position (#(1, 1) = upper left).
(However, the character string specified by text: is not displayed at this time. Please tell me how to display text characters .... Problem (1))
I have intended to have coded a Python script to draw with .add_widget method followed to the kvLang.
In this script, the yellow ellipse appears in the lower right instead of the expected Cell position ((2, 2) => lower left) ... problem (2)
For the purpose, it is necessary to add a widget to Grid Laytout using the .add_widget method so that the shape drawn in canvas can be displayed in the cell.
Please tell us how to solve it.
from kivy.graphics.context_instructions import Color
from kivy.graphics.vertex_instructions import Ellipse
from kivy.lang import Builder
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.app import App
Builder.load_string('''
<MyGridLayout#GridLayout>:
cols: 2
Label:
text:"From Kv_1" #(1)Not show. What's problem?
canvas:
Color:
rgb:0,0,1
Ellipse:
pos:self.pos
size:self.size
''')
class MyGridLayout(GridLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.add_widget(Button(text="From_Py_1"))
self.add_widget(Button(text="From_Py_2"))
labl = Button(text="From_Py_canvas_1")
self.add_widget(labl)
with labl.canvas:
# (2) Expected to draw at cell(2,2) which is same locaton as the lable of "From_Py_canvas_1" but not.
Color(rgb=(1, 1, 0))
Ellipse(pos=labl.pos, size_hint=labl.size_hint)
class MyApp(App):
def build(self):
return MyGridLayout()
if __name__ == '__main__':
MyApp().run()
Problem 1: You just need to use canvas.before: instead of canvas: in your kv. This draws the ellipse before the text, instead of after (obscuring the text).
Problem 2: Your Ellipse is the using the current properties of the labl, which are default values until the app is displayed. To fix that, create the Ellipse after by using Clock.schedule_once(). In the modified code below, I saved a reference to labl in order to access it in the draw_yellow_ellipse() method:
from kivy.clock import Clock
from kivy.graphics.context_instructions import Color
from kivy.graphics.vertex_instructions import Ellipse
from kivy.lang import Builder
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.app import App
Builder.load_string('''
<MyGridLayout#GridLayout>:
cols: 2
Label:
text:"From Kv_1" #(1)Not show. What's problem?
canvas.before:
Color:
rgb:0,0,1
Ellipse:
pos:self.pos
size:self.size
''')
class MyGridLayout(GridLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.add_widget(Button(text="From_Py_1"))
self.add_widget(Button(text="From_Py_2"))
self.labl = Button(text="From_Py_canvas_1")
self.add_widget(self.labl)
Clock.schedule_once(self.draw_yellow_ellipse)
def draw_yellow_ellipse(self, dt):
with self.labl.canvas:
# (2) Expected to draw at cell(2,2) which is same locaton as the lable of "From_Py_canvas_1" but not.
Color(rgb=(1, 1, 0))
Ellipse(pos=self.labl.pos, size_hint=self.labl.size_hint)
class MyApp(App):
def build(self):
return MyGridLayout()
if __name__ == '__main__':
MyApp().run()
Also, I don't think the Ellipse honors size_hint. Perhaps you meant to use size=self.labl.size. And if you do that, you will again have an Ellipse obscuring, in this case, your Button.
I had found a similar topic at stackoverflow but unluckily it didn't help me.
It's the first time I try to seriously program a GUI and I'm really getting mad.
I'm doing one step at a time, towards what I will finally need.
Now I'm trying to add a simple drop down menu in the top left corner of my widget, whose element should call a function whenever they are selected. I really looked for this in kivy documentation, and in this forum but I can't really solve this.
import multiprocessing
from mesh import MeshApp
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
import os
MAINDIR = os.path.dirname(os.path.realpath(__file__))
categories = {}
def getCategories():
for dir in os.walk(MAINDIR):
if len(dir[1]) == 0:
filelist = set()
for mesh in dir[2]:
filelist.add(mesh.replace('_FRONT.png','').replace('_SIDE.png','').replace('_TOP.png',''))
categories.update({dir[0]: filelist})
#class CategoriesList(DropDown):
# pass
class MainWindow(Widget):
def __init__(self):
#self.categorieslist = CategoriesList()
categories_list = DropDown()
for i in categories.keys():
btn = Button(text=i.replace(MAINDIR, ''), size_hint_y=None, height=30)
btn.bind(on_release=lambda btn: categories_list.select(btn.text))
categories_list.add_widget(btn)
mainbutton = Button(text='Choose directory', size_hint=(1, 1))
mainbutton.bind(on_release=categories_list.open)
categories_list.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x))
#and now???
class RenderApp(App):
def build(self):
self.launchMeshApp()
return MainWindow()
def launchMeshApp(self):
app = MeshApp()
p = multiprocessing.Process(target=app.run)
p.start()
if __name__ == '__main__':
getCategories()
RenderApp().run()
And:
#:kivy 1.9.1
<MainWindow>:
canvas.before:
Color:
rgba: 0.6, 0.6, 1, 1
Rectangle:
pos: self.pos
size: self.size
canvas:
Color:
rgba: 0, 0, 0, 0.5
Rectangle:
pos: 0, self.height * 5 / 6 - 1
size: self.width, 2
I've created the dropdown as seen in the docs and in several other forum. But I need to place it in the top left corner, and I never found, or understood, the way to do this. Moreover I didn't get how to make them call a function with a parameter whenever they are clicked.
Thank you very much
EDIT: I don't know why but the first line with "Hi all" is automatically deleted
I don't know about the dropdown menu, but I can answer the data one.
When you bind a callback, the first argument you receive will be which widget that is bound to the callback. So the idea is to create a class that uses Button as its base class, then you can define whatever extra information you need.
Here is a rough, non tested example based on the button API example:
class MyAwesomeButton(Button):
def __init__(self, **kwargs):
super(MyAwesomeButton, self).__init__(**kwargs)
self.my_data = {} # enter your data here
def callback(instance):
print('The button <%s> is being pressed' % instance.text)
print instance.my_data
btn1 = MyAwesomeButton(text='Hello world 1')
btn1.bind(on_press=callback)
btn2 = MyAwesomeButton(text='Hello world 2')
btn2.bind(on_press=callback)
I wanted to make a kivy game with an stickman running around the screen, and as soon as you click on it, the stickman is removed.
I tried to remove the enemy widget by using Place.remove_widget(Enemy), but the Program crashed an I got this error message:
TypeError: unbound method remove_widget() must be called with Place instance as first argument (got WidgetMetaclass instance instead)
Here is my source code:
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.properties import NumericProperty
from kivy.clock import Clock
from kivy.animation import Animation
class Place(FloatLayout):
pass
class Enemy(Widget):
velocity = NumericProperty(1)
def __init__(self, **kwargs):
super(Enemy, self).__init__(**kwargs)
Clock.schedule_interval(self.Update, 1/60.)
def Update(self, *args):
self.x -= self.velocity
if self.x < 1:
self.velocity = 0
def on_touch_down(self, touch):
if self.collide_point(*touch.pos):
print 'es geht'
self.velocity = 0
Place.remove_widget(Enemy)
ROOT = Builder.load_string('''
Place:
Button:
text: 'Go Back'
size_hint: 0.3, 0.1
pos_hint: {"x": 0, 'y':0}
Enemy:
pos: 400, 100
<Enemy>:
Image:
pos: root.pos
id: myimage
source: 'enemy.png'
''')
class Caption(App):
def build(self):
return ROOT
if __name__ == '__main__':
Caption().run()
Place.remove_widget(Enemy)
This is the problem - you aren't trying to remove an instance of the Enemy class from an instance of the Place class, but instead trying to remove the actual class itself from the other. This is the difference between a = Place and a = Place() - the former is the instructions for how to make a Place, the latter is an actual individual Place instance.
In this case you could probably do self.parent.remove_widget(self); self.parent is the Place instance containing the Enemy instance.
I'm trying to display an image as an intro to an app. Every time the user runs the program, it should display the image, then when press, it should open a few buttons which are popups.
from kivy.app import runTouchApp
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.popup import Popup
from kivy.uix.image import Image
from kivy.lang import Builder
kv = '''
BoxLayoutWithPopup:
orientation:'horizontal'
spacing:10
padding:5
Image:
source: 'appintro.png'
size:100,100
on_press:
root.pop1()
'''
#Helpme:
#title: 'Help Me'
#content: 'helpme.png'
# size_hint: None,None
# pos_hint: 700,320
# size: 250,100
#Games:
# title: 'Games'
# content: 'helpme.png'
# size_hint: None,None
# pos_hint: 100,20
# size: 250,100
class BoxLayoutWithPopup(BoxLayout):
def pop1(self):
# root.add_widget(HelpMe)
# root.add_widget(Games)
helpme = Popup(title='helpme', content=Image(source='helpme.png'),
size_hint=(.8, .8), pos=(1,30), size=(200, 200))
helpme.open()
#def pop2(self):
games = Popup(title='games', content=Image(source='games.png'),
size_hint=(.5, .5), pos=(20,80), size=(200,200))
games.open()
settings = Popup(title='settings', content=Image(source='settings.png'),
size_hint=(.3, .3), pos=(1,1), size=(400, 400))
settings.open()
if __name__ == '__main__':
runTouchApp(Builder.load_string(kv))
Can anyone help me identify what is wrong with this code? I'm trying to display an intro when the app is initialized, which opens the main page when pressed, but the image for the intro and images for the popups are not being displayed. I also tried moving the popup positions, it seem to not be working. please help me.
You are passing a tuple as the pos_hint when it expects a dict. If you want to specify the position, you should use pos instead - so instead of pos_hint=(1,1) you would use pos=(1,1). If you want to specify a position relative to the parent, you can use pos_hint={'x': 0, 'y': 0} for example.
import os,sys,random
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.graphics import Color, Rectangle
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.image import Image
from kivy.uix.screenmanager import ScreenManager, Screen , SlideTransition
from kivy.animation import Animation
from kivy.properties import StringProperty
class Page(Screen):
source = StringProperty()
class Imglayout(FloatLayout):
def __init__(self,**args):
super(Imglayout,self).__init__(**args)
with self.canvas.before:
Color(0,0,0,0)
self.rect=Rectangle(size=self.size,pos=self.pos)
self.rootpath = os.path.dirname(os.path.realpath(sys.argv[0]))
self.images=[]
for img in os.listdir(self.rootpath+'/images'):
self.images.append(self.rootpath+'/images/'+img)
self.index=random.randint(0,len(self.images)-1)
self.im=Image(source=self.images[self.index])
self.im.keep_ratio= False
self.im.allow_stretch = True
#self.add_widget(self.im)
self.sm = ScreenManager(transition=SlideTransition())
self.page1=Page(name='page1', source = self.images[self.index])
self.page2=Page(name='page2', source = self.images[self.index+1])
self.sm.add_widget(self.page1)
self.sm.add_widget(self.page2)
self.bind(size=self.updates,pos=self.updates)
def updates(self,instance,value):
self.rect.size=instance.size
self.rect.pos=instance.pos
def on_touch_down(self,touch):
if self.collide_point(*touch.pos):
if(self.sm.current == 'page1'):
next='page2'
page=self.page2
else:
next='page1'
page=self.page1
self.index=(self.index+1)%len(self.images)
page.source = self.images[self.index]
page.background.scale = 1.0
self.sm.transition=SlideTransition()
self.sm.current = next
anim = Animation(
scale=page.background.scale*1.3,
duration=15.0
)
anim.start(page.background)
return True
return False
class MainTApp(App):
def build(self):
root = BoxLayout(orientation='vertical',spacing=10)
c = Imglayout()
root.add_widget(c)
cat=Button(text="Categories",size_hint=(1,.05))
cat.bind(on_press=self.callback)
root.add_widget(cat);
return root
def callback(self,value):
print "CALLBACK CAT"
if __name__ == '__main__':
MainTApp().run()
Taking some hints from here i made the above program. It says that Page does not have a background attribute in both my and the referenced code. Its kind of obvious since there is no background attribute. I thought it inherited that from Screen. I am trying to make a slideshow kind of thing. But i cant find any information on how to set the background of a screen.
And if i comment out everything with .background and run the app. click on the black space, then i start getting this error continuously on the terminal
[ERROR ] [OSC ] Address 127.0.0.1:3333 already in use, retry
in 2 second
And i still dont get any background on the app.(its all black.)
and if i print self.sm.current on the touich function. Then i find that its always page1, it never changes.
The Kivy Guide explains how to add a background to a Widget. Briefly, you can do it in Python using the following code which binds to the position and size of the widget to make sure the background moves with the widget.
with widget_instance.canvas.before:
Color(0, 1, 0, 1) # green; colors range from 0-1 instead of 0-255
self.rect = Rectangle(size=layout_instance.size,
pos=layout_instance.pos)
widget_instance.bind(size=self._update_rect, pos=self._update_rect)
...
def _update_rect(self, instance, value):
self.rect.pos = instance.pos
self.rect.size = instance.size
Or you can do it more naturally with the kv language e.g.
MyWidget:
canvas.before:
Color:
rgba: 0, 1, 0, 1
Rectangle:
# self here refers to the widget i.e screen
pos: self.pos
size: self.size