A
A
Andrey Gurtovenko2022-03-21 15:18:42
Python
Andrey Gurtovenko, 2022-03-21 15:18:42

How to make a button call a function with an argument?

Making my first steps in kivy. I'm trying to create just 4 buttons, each one just presses the arrows on the keyboard using pyautogui.

The code:

# Импорт всех классов
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.core.window import Window

import pyautogui as pag


class MyApp(App):
  
  # Создание всех виджетов (объектов)
  def __init__(self):
    # Глобальные настройки
    self.title = 'Controller'
    
    super().__init__()
    self.btn_left=Button(text="Left", background_color ="c24b99")
    self.btn_down=Button(text="Down", background_color="00ffff")
    self.btn_up=Button(text="Up", background_color="12fa05")
    self.btn_right=Button(text="Right", background_color="f9393f")

  # Основной метод для построения программы
  def build(self):
    # Все объекты будем помещать в один общий слой
    box = BoxLayout()


    box.add_widget(self.btn_left)
    box.add_widget(self.btn_down)
    box.add_widget(self.btn_up)
    box.add_widget(self.btn_right)


    return box


# Запуск проекта
if __name__ == "__main__":
  MyApp().run()


Is it possible to make all these buttons be controlled by the same function, but with a different argument?

PS Working in Visual Studio Code, Python version is 3.9.10 and kivy is 2.0.0.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Gnifajio, 2022-03-23
@FanaticExplorer

self.btn_left .bind(on_press = lambda: pyautogui.press("left"))
self.btn_down .bind(on_press = lambda: pyautogui.press("down"))
self.btn_up   .bind(on_press = lambda: pyautogui.press("up"))
self.btn_right.bind(on_press = lambda: pyautogui.press("right"))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question