Changing image in widget - Kivy - Python - python

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
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.bind(size=self.updates,pos=self.updates)
def updates(self,instance,value):
self.rect.size=instance.size
self.rect.pos=instance.pos
class MainTApp(App):
im=Image(source='img1.jpg')
def build(self):
root = BoxLayout(orientation='vertical')
c = Imglayout()
root.add_widget(c)
self.im.keep_ratio= False
self.im.allow_stretch = True
cat=Button(text="Categories",size_hint=(1,.07))
cat.bind(on_press=self.callback)
c.add_widget(self.im)
root.add_widget(cat);
return root
def callback(self,value):
self.im=Image(source='img2.jpg')
if __name__ == '__main__':
MainTApp().run()
What i am trying to do here, is change the image first loaded during object creation, which is shown when the app starts, and then change it when the button cat is pressed. I am trying it to do this way but it isnt happening. I would eventually want it to change with a swipe gesture.(with a little bit of swipe animation like it happens in the phone
what i am trying to build is a slideshow, which will change image in t seconds, unless swiped, and then when a new image comes the timer resets.
When the category button is pressed the image will not be there and a list of categories to select from. and when an item from the list is touched the images from that list will be displayed on the screen.
And at the end when everything has been done i would want to make it such that it automatically detects categories(based on directories in a specified location.) and then all the images will be available to it.(that is not telling it explicitly how many images and what images.)
But, i am not able to do the first thing, so i would really like some help on that. And maybe a few pointers on how to achieve the other things as well.

def callback(self,value):
self.im=Image(source='img2.jpg')
Your problem is in the definition of the callback. You create a new image with the new source, but you don't do anything with it, like adding it to your widget tree.
What you really want to do is modify the source of the existing image:
def callback(self, instance, value):
self.im.source = 'img2.jpg'
This will immediately replace the source of the existing image, which will immediately update in your gui. Note that I also added an instance parameter, which will be passed to the callback so you need to catch it or you'll crash with the wrong number of arguments.
Also, I'd define your image inside build rather than as a class level variable. I'm not sure if the current way will actually cause you problems, but it could in some circumstances.

Related

Kivy button example closes immediately when testing

I'm trying to learn Kivy using their examples, however I'm having an issue. I'm using their button doc example:
from kivy.uix.button import Button
def callback(instance):
print('The button <%s> is being pressed' % instance.text)
btn1 = Button(text='Hello world 1')
btn1.bind(on_press=callback)
btn2 = Button(text='Hello world 2')
btn2.bind(on_press=callback)
However, the program runs and immediately closes. I assumed maybe its tkinter, where the program runs on a constant loop and you need to add something at the end so it doesn't close, but I couldn't find anything on their docs about that.
To reiterate, I don't get any errors, the file just runs, I get a very brief pop up, and then it ends. I don't get an interface.
Firstly, kivy need to loop for control all own functions. So we need a App class and have to return our layouts directly or layouts under Screen Manager. In Kivy-Button documentation, Kivy shows you only related part. So there is a no any App class or loop for control.So program runs and closes immediately because app class doesn't loop window.
If you're beginner and trying to learn kivy from documentation, you need to figure how Kivy actually works and how documentation explain things. I'm sharing this code below for you, you need to understand add-remove widgets ,set layouts,... in kivy from documentations or search for full-code examples not part.
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
class TestLayout(BoxLayout):
def __init__(self, **kwargs):
super(TestLayout, self).__init__(**kwargs)
self.orientation = 'vertical'
but1 = Button(text='Button1')
self.add_widget(but1)
but2 = Button(text='Button2')
self.add_widget(but2)
class MyApp(App):
def build(self):
return TestLayout()
if __name__ == '__main__':
MyApp().run()
When you understand how it works, you should start to use Screen Manager for easily create pages, send-get values (and many things) for your applications.I hope these helps you at the beginning. Good luck.

Buttonbehaviour with buttons generated dynamically by a python list (kivy) [duplicate]

This question already has answers here:
Lambda in a loop [duplicate]
(4 answers)
Closed 3 years ago.
I have spend the last few days making an app that I want to implement on a raspberry pi coupled to a 10 inch touchscreen. I am making this app for a student housing association here in Germany.
So the idea is to have the raspberry with the touchscreen installed on/next to/on top of (not sure yet), the common fridge. The fridge only holds drinks in .5L bottles format which cost 0.80€ to 1.10€ each. We don't pay immediately, we just write down our consummations on a list.
What I am trying to do is an app with the kivy library in which I can just click on my name, get a drink and the app would save my consumptions, what I already paid and save these infos in a CSV file. In order to do that I have to generate a number of buttons dynamically (the names of the poeple on the list) with kivy, which I did. But now it seems that I cannot assign them any function when they get pressed. More precisely, the index of each button doesn't seem to have any effect. I don't really know how to explain it so let's look at some code:
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
class grid(App):
button = [0 for i in range(25)]
def build(self):
main = GridLayout(cols = 5)
for i in range(25):
self.button[i] = Button(text = str(i))
self.button[i].bind(on_release =lambda x: grid.printString(str(i)))
main.add_widget(self.button[i])
return main
def printString(string):
print(string)
app = grid()
app.run()
So this isn't my actual code, it's an example that illustrates the problem. The output I get is 24 for each button I click. What I want is that each button prints it's own index in the button[] list. I have been trying to make this work for hours and I haven't found anything that worked. If anyone knows how to assign these button behaviors correctly, I would be really grateful for your input.
Declare a class CustomButton with inheritance of Button widget
Use on_touch_down event and check for collision
Assign id when creating CustomButton
Example
main.py
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
class CustomButton(Button):
def on_touch_down(self, touch):
if self.collide_point(*touch.pos):
print("Button.id=", self.id)
return True
return False
class grid(App):
def build(self):
main = GridLayout(cols=5)
for i in range(25):
button = CustomButton(id=str(i), text=str(i))
main.add_widget(button)
return main
app = grid()
app.run()

kivy find all TextInputs

I was trying to register all TextInputs and Spinner in my GUI.
Each of these does have a variable gid.
The problem with the root_widget.walk() method is that I have different tabs and it does not load the widgets that have not been displayed yet.
However this is not my biggest problem.
The thing is that the walk()method does only show Widgets and not TextInputs nor Spinner.
My question now is: How do you traverse EVERY object (TextInputs/Spinner etc.) including those that have not been displayed yet (in a different tab)
I am very happy for any kind of help or advice.
Greetings, Finn
The walk() widget method does visit all child widgets (including TextInput and Spinner. If you are using TabbedPanel as your root widget, then the following will register all your widgets (if it is called by a binding to on_draw):
registered = False
def on_draw(*args):
global registered
if registered:
return # just to avoid running this many times
registered = True
app = App.get_running_app()
for tab in root_widget.tab_list: # assumes root_widget is a TabbedPanel
if tab.content is not None:
for widget in tab.content.walk():
app.register_widget(widget)
A similar construct could be done if you are using a ScreenManager as your root widget.

Programmatically controlling a carousel in kivy

I'm new with kivy, but I have decent experience with Python and Tkinter. I'm trying to control a carousel in kivy programmatically. Essentially, I have an external python program which I want to use to automatically switch images in the carousel. To make an example, I have some code in another file:
import time
while True:
time.sleep(1)
#do something to control the carousel
and then I have my kivy app:
import kivy
from kivy.app import App
from kivy.uix.carousel import Carousel
from kivy.uix.image import AsyncImage
class CarouselApp(App):
self.srcs = ["/a/bunch.png", "/of/paths.jpg", "/to/images.png."]
def build(self):
self.carousel = Carousel(direction="right")
for i in range(0, len(self.srcs)):
src = self.srcs[i]
image = AsyncImage(source=src, allow_stretch=True)
self.carousel.add_widget(image)
return self.carousel
if __name__ == "__main__":
CarouselApp().run()
I would like to be able to control which slide is displayed in the carousel using the top code, but I'm not sure how I would go about doing that, since I can't execute anything after App.run()
I have investigated kivy's Clock module, but I'm not sure that would work for me since I want to switch slides when certain conditions are satisfied rather than on a time basis. The time example I gave is simply an example of my line of thinking.
Any help would be greatly appreciated!
I strongly suggest using a Kivy file to handle this situation. Second, AsyncImage is used when you want to use an image that will be downloaded from the Internet, and as I can see you have the images you are going to use are locally stored, so use Image instead.
I think you should implement the method on_start in the class which is extending App (CarouselApp in this case) and schedule a function using Clock as,
def on_start(self):
Clock.schedule_interval(self.my_callback, 1)
Then in the same class (CarouselApp) you should define my_callback:
def my_callback(self, nap):
if condition_is_satisfied: # this is supposed to be your condition
# control carousel

Kivy: Add ScreenManager to window not as root?

I'm using Kivy and I'm trying to setup a ScreenManager, but I don't want that ScreenManager to be the root widget in my window. Here's a test code snippet that demonstrates what I'm trying to do. (This code demonstrates my problem.)
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.widget import Widget
class MyRootWidget(Widget):
def __init__(self, **kwargs):
super(MyRootWidget, self).__init__(**kwargs)
self.screen_manager = ScreenManager()
self.add_widget(self.screen_manager)
# self.add_widget(Label(text='label direct'))
class MyApp(App):
def build(self):
root = MyRootWidget()
new_screen = Screen(name='foo')
new_screen.add_widget(Label(text='foo screen'))
root.screen_manager.add_widget(new_screen)
root.screen_manager.current = 'foo'
for x in root.walk():
print x
return root
if __name__ == '__main__':
MyApp().run()
When I run this code, the window is blank, though I would expect that it would show the text "foo screen"?
The print of the walk() command shows that the root widget contains the screenmanager, my screen, and the label, like this:
<__main__.MyRootWidget object at 0x109d59c80>
<kivy.uix.screenmanager.ScreenManager object at 0x109eb4ae0>
<Screen name='foo'>
<kivy.uix.label.Label object at 0x109ecd390>
So that's working as I would expect.
If I uncomment the line which adds the label widget directly to the root widget, that label shows up as expected.
Also if I change the MyApp.build() method so that it returns new_screen instead of returning root, it also works in that I see the label "foo screen" on the display.
BTW, the reason I want to not have the screen manager be the root widget is because I want to be able to print messages (almost like popups) on the screen in front of whichever screen is active (even if screens are in the process of transitioning), so I was thinking I would need the screen manager not to be root in order to do that?
Also my ultimate goal is to have multiple "quadrants" in the window, each with its own screen manager, so I was thinking I needed to make sure I can show screen managers that are not the root widget in order to do this.
So if there's a better way for me to do this, please let me know. Also I do not want to use .kv files for this as I want to set this entire environment up programmatically based on other config options (which I've left out of this example.)
Overall though I wonder if anyone knows why this code doesn't work?
Thanks!
Brian
The problem is you are sticking your ScreenManager in a generic Widget. If you put it in a Layout, it will display properly, ie:
class MyRootWidget(BoxLayout):
There are several layouts available: http://kivy.org/docs/gettingstarted/layouts.html

Categories

Resources