python kivy button and triggering a function

i m relatively new to kivy and i wanted to make a app but i m stuck at how to call a function by clicking on a button but i seem to face many problems .After hours of googling i still couldn t come up with a working code . i want to display the button first and then on click the button disappears and the function is executed.

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


class maingame(GridLayout):
  def __init__(self, **kwargs):
    super().__init__(**kwargs)
    self.cols = 1
    self.rows = 1 
  def potato(self):
  
    self.add_widget(Label(text="potato is great")



class myApp(App):

  def build(self):
    cake = maingame()
    btn = Button(text="start " ,size=(90,90))
    btn.bind(on_press=cake.potato)
    cake.add_widget(btn)
    return maingame()

        

if __name__ == "__main__":

  myApp().run()

python – add_widget () with Matplotlib and Kivy

I can plot a graph with FigureCanvasKivyAgg from Matplotlib library for apps in kivy library, however when I use the add_widget, ends up occupying the entire visual field of the screen and I have no way to change the figure or perform other operations.

I want to specify a fixed space on the screen, for example: When working on Android screens (360×640), the figure will occupy (300×550), or any other percentage.

I tried to perform this operation putting something in this direction, without success in .kv file:

canvas:
    Rectangle:
       pos: (50,50)
       size: (100,100)

And this is the code that I'm working on (main.py and meuprograma.kv):

main.py

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
import matplotlib.pyplot as plt
import pandas as pd
from kivy.garden.matplotlib.backend_kivyagg import FigureCanvas
import numpy as np

def grafico1():
    np.random.seed(19680801)
    plt.rcdefaults()
    fig, ax = plt.subplots()

    people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
    y_pos = np.arange(len(people))
    performance = 3 + 10 * np.random.rand(len(people))
    error = np.random.rand(len(people))

    ax.barh(y_pos, performance, xerr=error, align='center')
    ax.set_yticks(y_pos)
    ax.set_yticklabels(people)
    ax.invert_yaxis() 
    ax.set_xlabel('Performance')
    ax.set_title('Quão rápido você quer ir hoje?')
    wid = FigureCanvas(fig)
    return wid

def grafico2():
    np.random.seed(2234893)
    plt.rcdefaults()
    fig, ax = plt.subplots()

    people = ('Miles', 'Jhoson', 'Henry', 'Slim', 'Jim')
    y_pos = np.arange(len(people))
    performance = 3 + 10 * np.random.rand(len(people))
    error = np.random.rand(len(people))

    ax.barh(y_pos, performance, xerr=error, align='center')
    ax.set_yticks(y_pos)
    ax.set_yticklabels(people)
    ax.invert_yaxis() 
    ax.set_xlabel('Performance')
    ax.set_title('Quão rápido você quer ir hoje?')
    wid = FigureCanvas(fig)
    return wid

class Gerenciador(ScreenManager):
    pass

class Menu(Screen):
    pass

class Sensores(Screen):
    pass

class Grafico(Screen):

    def add_plot1(self):
        self.add_widget(grafico1())
    def add_plot2(self):
        self.add_widget(grafico2())


class MeuProgramaApp(App):
    def build(self):
        return Gerenciador()

MeuProgramaApp().run()

myprogram.kv

:
     Menu:
         name: 'menu'
     Sensores:  
         name: 'sensores'
     Grafico:
         name: 'grafico'

:
    BoxLayout:
        orientation: 'vertical'
        padding: 200
        spacing: 50
        Button:
            text: 'Lista de Sensores'
            on_release: root.manager.current = 'sensores'
        Button:
            text: 'Sair'
            on_release: app.stop()

:
    BoxLayout:
        orientation: 'vertical'
        padding: 50
        spacing: 10
        Button:
            text: 'Sensor 01'
            on_release:
                root.manager.current = 'grafico'
        Button:
            text: 'Sensor 02'
        Button:
            text: 'Sensor 03'
        Button:
            text: 'Sensor 04'

:
    BoxLayout:
        Button:
            size_hint: 0.5, 0.09
            pos_hint: {"x": .3 , "y": .2}
            text: "Grafico 1"
            on_release: root.add_plot1()
        Button:
            size_hint: 0.5, 0.09
            pos_hint: {"x": .7 , "y": .2}
            text: "Grafico 1"
            on_release: root.add_plot2()

The first image below is a sketch of the part of the screen that would occupy the graph and the second image is how the graph is currently occupying.

Something also important, that I still don't know, since I have two plots to plot, will the plot of the second plot take place on the first plot, or will I have to clean the first plot with some "clear"?

insert image description here
insert image description here

How to run Kivy app on ubuntu-16 (CLI)?

kivy can be run on ubuntu CLI.
I am using ubuntu-16.
If anyone has a solution, please help me !!!
Thank you.

(INFO   ) (Logger      ) Record log in /home/user/.kivy/logs/kivy_20-03-13_3.txt
(INFO   ) (Kivy        ) v1.11.1
(INFO   ) (Kivy        ) Installed at "/usr/lib/python3/dist-packages/kivy/__init__.py"
(INFO   ) (Python      ) v3.5.2 (default, Oct  8 2019, 13:06:37)
(GCC 5.4.0 20160609)
(INFO   ) (Python      ) Interpreter at "/usr/bin/python3"
(INFO   ) (Factory     ) 184 symbols loaded
(INFO   ) (Image       ) Providers: img_tex, img_dds, img_pil, img_gif (img_sdl2, img_ffpyplayer ignored)
(CRITICAL) (Window      ) Unable to find any valuable Window provider. Please enable debug logging (e.g. add -d if running from the command line, or change the log level in the config) and re-run your app to identify potential causes
egl_rpi - ImportError: cannot import name 'bcm'
  File "/usr/lib/python3/dist-packages/kivy/core/__init__.py", line 63, in core_select_lib
    fromlist=(modulename), level=0)
  File "/usr/lib/python3/dist-packages/kivy/core/window/window_egl_rpi.py", line 12, in 
    from kivy.lib.vidcore_lite import bcm, egl

sdl2 - ImportError: libSDL2_image-2.0.so.0: cannot open shared object file: No such file or directory
  File "/usr/lib/python3/dist-packages/kivy/core/__init__.py", line 63, in core_select_lib
    fromlist=(modulename), level=0)
  File "/usr/lib/python3/dist-packages/kivy/core/window/window_sdl2.py", line 27, in 
    from kivy.core.window._window_sdl2 import _WindowSDL2Storage

x11 - ImportError: No module named 'kivy.core.window.window_x11'
  File "/usr/lib/python3/dist-packages/kivy/core/__init__.py", line 63, in core_select_lib
    fromlist=(modulename), level=0)

(CRITICAL) (App         ) Unable to get a Window, abort.

python – Upside down widgets on Kivy

I have a problem running any Kivy screen, since it always appears backwards. This problem is only with that specific library, the others I use work normally.

A simple code like:

from kivy.app import App
from kivy.uix.button import Label

class TestApp(App):
    def build(self):
         return Label( text = 'Hello World' )

TestApp().run()

It results in an upside down screen, as in this image:

insert image description here

python – Kivy problem of the POS system

I have some problems with the Kivy POS system code here, I need help please

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from utils.datatable import DataTable

from collections import OrderedDict
from pymongo import MongoClient

class AdminWindow(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        content = self.ids.content
        clients = self.get_clients()
        clients_table = DataTable(table=clients)
        content.add_widget(clients_table)

    def get_clients(self):

        mongoClient = MongoClient()
        db = mongoClient.consumini
        clients = db.clients
        _clients = OrderedDict(
            names = {},
            usernames = {},
            passwords = {}
        )
        names = ()
        usernames = ()
        passwords = ()


        for client in clients.find():
            names.append(client('name'))
            usernames.append(client('username'))
            passwords.append(client('password'))
        clients_length = len(names)
        index = 0
        while index < clients_length:
            _clients('names')(index) = names(index)
            _clients('usernames')(index) = usernames(index)
            _clients('passwords')(index) = passwords(index)

            index += 1
        return _clients

    def get_products(self):

        mongoClient = MongoClient()
        db = mongoClient.consumini
        products = db.stocks
        _stocks = OrderedDict()
        _stocks('product_code') = {}
        _stocks('product_name') = {}
        _stocks('in_stock') = {}
        _stocks('sold') = {}
        _stocks('order') = {}
        _stocks('last_purchase') = {}

        product_code = ()
        product_name = ()
        in_stock = ()
        sold = ()
        order = ()
        last_purchase = ()


        for product in products.find():
            product_code.append(product('product_code'))
            product_name.append(product('product_name'))
            in_stock.append(product('in_stock'))
            sold.append(product('sold'))
            order.append(product('order'))
            last_purchase.append(product('last_purchase'))

        products_length = len(product_code)
        index = 0

        while index < products_length:
            _stocks('product_code')(index) = product_code(index)
            _stocks('product_name')(index) = product_name(index)
            _stocks('in_stock')(index) = in_stock(index)
            _stocks('sold')(index) = sold(index)
            _stocks('order')(index) = order(index)
            _stocks('last_purchase')(index) = last_purchase(index)

            index += 1
        return _stocks

class AdminApp(App):
     def build(self):
         return AdminWindow()

if __name__=="__main__":
    AdminApp().run()

And that is the mistake

>  Traceback (most recent call last):    File
> "c:/Users/pedro/Desktop/Consumini/src/admin/admin.py", line 94, in
> 
>      AdminApp().run()    File "C:UserspedroAppDataLocalProgramsPythonPython37libsite-packageskivyapp.py",
> line 829, in run
>      root = self.build()    File "c:/Users/pedro/Desktop/Consumini/src/admin/admin.py", line 91, in
> build
>      return AdminWindow()    File "c:/Users/pedro/Desktop/Consumini/src/admin/admin.py", line 14, in
> __init__
>      clients_table = DataTable(table=clients)    File "c:UserspedroDesktopConsuminisrcadminutilsdatatable.py", line
> 33, in __init__
>      super().__init__(**kwargs)    File "C:UserspedroAppDataLocalProgramsPythonPython37libsite-packageskivyuixboxlayout.py",
> line 145, in __init__
>      super(BoxLayout, self).__init__(**kwargs)    File "C:UserspedroAppDataLocalProgramsPythonPython37libsite-packageskivyuixlayout.py",
> line 76, in __init__
>      super(Layout, self).__init__(**kwargs)    File "C:UserspedroAppDataLocalProgramsPythonPython37libsite-packageskivyuixwidget.py",
> line 350, in __init__
>      super(Widget, self).__init__(**kwargs)    File "kivy_event.pyx", line 243, in kivy._event.EventDispatcher.__init__  TypeError:
> object.__init__() takes no arguments

How to use a button to activate an event in python kivy

I'm trying to use the button in kivy, and what I wanted is to click on the button, and a message appears next to the button in TextInput, but I couldn't do this. Anyone know how to do this? Thank you

python: capture the properties of a dynamically added Kivy button

I have a problem, I have an application created in Python and Kivy that has a screen that once accessed, creates some buttons dynamically. I would like to know how to capture the text of the button that was clicked.

Python:

def on_enter(self):
    lista_series =(1,2,3,4,5,6,7,8)
    for i in lista_series:
        self.ids.grid.add_widget(Button(text=str(i)))

By clicking on any button, I would like the text of the selected button to return.

kivy – Buildozer failed when: git clone python-for-android

When I run "buildozer -v android debug", I ran into these problems, how can I fix it?

it is a virtual box with ubuntu kivy-buildozer installed

& # 39; & # 39; & # 39;

kivy@kivyvm:~/Desktop$ buildozer android_new debug
# Check configuration tokens
# Ensure build layout
# Check configuration tokens
# Preparing build
# Check requirements for android
# Install platform
# Command failed: git clone -b master --single-branch https://github.com/kivy/python-for-android.git python-for-android-master
# 
# Buildozer failed to execute the last command
# If the error is not obvious, please raise the log_level to 2
# and retry the latest command.
# In case of a bug report, please add a full log with log_level = 2

& # 39; & # 39; & # 39;

python – Installing Kivy 1.10.1 on Rasbian Buster

I found errors installing kivy 1.10.1.dev0 on my new raspeberri pi 4.

The source of error comes from the instruction:

sudo pip3 install git+https://github.com/kivy/kivy.git@master

after following the guide https://kivy.readthedocs.io/en/master/installation/installation-rpi.html#.
Give the error:

  building 'kivy.lib.vidcore_lite.egl' extension
  creating build/temp.linux-armv7l-3.7/tmp/pip-req-build-bsrs6yn7/kivy/lib/vidcore_lite
  arm-linux-gnueabihf-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/tmp/pip-req-build-bsrs6yn7/kivy/include -I/opt/vc/include -I/opt/vc/include/interface/vcos/pthreads -I/opt/vc/include/interface/vmcs_host/linux -I/usr/include/python3.7m -c /tmp/pip-req-build-bsrs6yn7/kivy/lib/vidcore_lite/egl.c -o build/temp.linux-armv7l-3.7/tmp/pip-req-build-bsrs6yn7/kivy/lib/vidcore_lite/egl.o
  /tmp/pip-req-build-bsrs6yn7/kivy/lib/vidcore_lite/egl.c:1:2: error: #error Do not use this file, it is the result of a failed Cython compilation.
   #error Do not use this file, it is the result of a failed Cython compilation.
    ^~~~~
   error: command 'arm-linux-gnueabihf-gcc' failed with exit status 1

  ----------------------------------------
  Failed building wheel for Kivy
  Running setup.py clean for Kivy
Failed to build Kivy
Installing collected packages: Kivy

python – Simple Kivy application for the Bootstrap algorithm

I have a very simlpe application built with Kivy, to perform the bootstrap algorithm (statistics). We must enter some samples in the form. x1, x2, ..., xn (These will be received as a string "x1, ..., xn" but then it will be transformed into a list of samples. From these samples, we will perform the bootstrap algorithm to approximate the average sampling distribution of the population.

We have the main widget using Widget Class, and we put a grid design of 1 row, 2 columns (on the left it will be for the options, on the right it will be the graph of the distribution). For the options grid, we place another 4×4 grid layout, with the last grid in a 3×1 grid layout consisting of the buttons for the result.

I wonder if there are better and efficient ways to write the code to run the application.


Example:

enter the description of the image here


Code:

import randomly

import matplotlib.pyplot as plt

from kivy.config import Config
Config.set (& # 39; graphics & # 39 ;, & # 39; resizable & # 39 ;, False)
from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg
from the import window kivy.core.window
of the import application kivy.app
from kivy.uix.widget import Widget
from kivy.uix.textinput import TextInput
from the import button kivy.uix.button
from kivy.uix.gridlayout import GridLayout


Window.clearcolor = (0,0,5,0.9,0.1)
Window size = (800, 400)


#Bootstrap method:


BootstrapMethod class (object):
def __init __ (self):
self.start_button = BootstrapButton (text = "Bootstrap")
self.layout = BootstrapGrid ()
self.options = BootstrapOptions ()


RunButtonLayout class (GridLayout):
def __init __ (self):
super () .__ init __ (rows = 3, cols = 1)
self.add_widget (PlotNormed (text = "Normed histogram"))
self.add_widget (PlotActual (text = "Actual histogram"))
self.add_widget (BootstrapButton (text = "Run bootstrap"))


PlotNormed class (Button):
def on_release (self):
xbars = self.parent.parent.parent.xbars
yes xbars! = None:
self.parent.parent.parent.ax.cla ()
self.parent.parent.parent.ax.hist (xbars, normed = True)
self.parent.parent.parent.fig.figure.canvas.draw ()


PlotActual class (Button):
def on_release (self):
xbars = self.parent.parent.parent.xbars
yes xbars! = None:
self.parent.parent.parent.ax.cla ()
self.parent.parent.parent.ax.hist (xbars)
self.parent.parent.parent.fig.figure.canvas.draw ()


BootstrapButton class (Button):
def on_release (self):
super () en_release ()
sample_string = self.parent.parent.sample_input.text.split (& # 39;, & # 39;)
self.samples = [float(i) for i in sample_string]
        self.bootstrap_algorithm ()

def bootstrap_algorithm (self):
xbars = []
        n = int (self.parent.parent.bootstrap_sample.text)
if n> len (own samples):
n = len (own samples)
nb = int (self.parent.parent.bootstrap_iteration.text)
for i in range (nb):
xbar = sum ([random.sample(self.samples, 1)[0] for j in rank (n)])/north
xbars.append (xbar)
self.parent.parent.parent.xbars = xbars
self.parent.parent.parent.ax.cla ()
self.parent.parent.parent.ax.hist (xbars)
self.parent.parent.parent.fig.figure.canvas.draw ()


BootstrapOptions class (GridLayout):
def __init __ (self):
super () .__ init __ (rows = 2, cols = 2)
self.sample_input = TextInput (text = "Sample input")
self.bootstrap_iteration = TextInput (text = "Number of startup iterations")
self.bootstrap_sample = TextInput (text = "Sample number for resampling")
self.run_layout = RunButtonLayout ()

self.add_widget (self.sample_input)
self.add_widget (self.bootstrap_iteration)
self.add_widget (self.bootstrap_sample)
self.add_widget (self.run_layout)


BootstrapGrid class (GridLayout):
def __init __ (self):
super () .__ init __ (rows = 1, cols = 2, fill = 5, spacing = 5)
fig, ax = plt.subplots ()
self.options = BootstrapOptions ()
self.add_widget (self.options)
self.fig = FigureCanvasKivyAgg (fig.)
self.ax = ax
self.add_widget (self.fig)
self.xbars = None



#################################################################################################### ####


Front class (Widget):
def __init __ (self):
super () .__ init __ ()
self.start ()

start def (auto):
self.bs = BootstrapMethod ()
self.add_widget (self.bs.layout)
self.bs.layout.size = (800, 400)


class mobilesuitApp (App):
def build (self):
root = Front ()
return root

app = mobilesuitApp ()
app.run ()