0

I'm trying to create a simple calculator. Below is my code:

from kivy.app import App from kivy.uix.floatlayout import FloatLayout from kivy.uix.button import Button class MyApp(App): def build(self): displays = ["(", ")", "C", "<-", "7", "8", "9", " / ", "4", "5", "6", " * ", "1", "2", "3", " - ", ".", "0", "=", " + "] iterator = 0 layout = FloatLayout() for row in range(5): for column in range(4): posx = column * .25 posy = .75 - (row * .18) button = Button(text=displays[iterator], pos_hint={"x": posx, "y": posy}, size_hint=(.25, .18), color=(1, 0, 1, 1), background_color=(0, 0, 0, 1), outline_color=(1, 0, 1, 1)) layout.add_widget(button) button.bind(on_press=lambda text=button.text: self.press(button_text=text)) iterator += 1 return layout def press(self, button_text): print("Called! ", button_text) MyApp().run() 

I'm certain I'm drawing issue with the following:

button.bind(on_press=lambda text=button.text: self.press(button_text=text)) 

Instead of passing the button's text, it's passing Called! kivy.uix.button.Button object at 0x0CAD6D88 (inside open close [lesser than greater than brackets HTML brackets?] But causes formatting issue here)

From my limited experience it seems as if I'm passing the button object itself as opposed to the intended text. This is my first attempt at using Kivy, help? Thanks.

1 Answer 1

1

You are using lambda incorrectly, it should be

button.bind(on_press=lambda button: self.press(button.text)) 

However, you don't need to use lambda functions, simply get text property of the instance passed to the callback:

from kivy.app import App from kivy.uix.floatlayout import FloatLayout from kivy.uix.button import Button class MyApp(App): def build(self): displays = ["(", ")", "C", "<-", "7", "8", "9", " / ", "4", "5", "6", " * ", "1", "2", "3", " - ", ".", "0", "=", " + "] iterator = 0 layout = FloatLayout() for row in range(5): for column in range(4): posx = column * .25 posy = .75 - (row * .18) button = Button(text=displays[iterator], pos_hint={"x": posx, "y": posy}, size_hint=(.25, .18), color=(1, 0, 1, 1), background_color=(0, 0, 0, 1), outline_color=(1, 0, 1, 1)) layout.add_widget(button) button.bind(on_press=self.press) iterator += 1 return layout def press(self, button): print("Called! ", button.text) MyApp().run() 
Sign up to request clarification or add additional context in comments.

1 Comment

Oh! This is one of the few times I've attempted to use lambda, and I pulled the majority of my code from a tkinter version. Can I ask how the press method knows which button is called? It seems like kivy passes the button object regardless. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.