Kivy: Instance of 'XXXX' has no 'bind' member - python

I am writing a program in Kivy, and whenever I am trying to bind a function to a Button or any other widget I get the following problem from pylint: "Instance of 'Button' has no 'bind' member" and the lines turn red. I am completely new to Kivy and this really bugs me.
The program works perfect when I execute it, and the compiler does not seem to have any problem with my bindings. What have I done wrong? Am I missing an import or anything, or is there something wrong with my environment?
Attached you find a code snippet I wrote as an example.
from kivy.app import App
from kivy.uix.button import Button
class MainApp(App):
def build(self):
button = Button(text='Hello from Kivy',
size_hint=(.5, .5),
pos_hint={'center_x': .5, 'center_y': .5})
button.bind(on_press=self.on_press_button)
return button
def on_press_button(self, instance):
print('You pressed the button!')
if __name__ == '__main__':
app = MainApp()
app.run()

It's likely that whatever linter you are using is not able to find the bind method because it comes from cython code. You need to configure it differently (if possible), or use a different linter.

Related

VScode doesn't use the kivy file

I'm new to programming and trying to use Kivy to create a simple game.
I am following a tutorial, and I'm using VSCode, but I can't understand why the code I write in the .kvfile doesn't is used by the main.pyfile.
I have two files in the directory.
main.py
from kivy.app import App
from kivy.uix.widget import Widget
class MainWidget(Widget):
pass
class TheLabApp(App):
pass
TheLabApp().run()
thelab.kv
MainWidget:
<MainWidget>:
Button:
text: 'Hello'
size: 400, 200
I have installed a Kivy extension, and of course the Kivy module. But when I run the code the only thing that appears is a black screen, without the button.
What is happening?
I found the solution. It is required to save the .kv file before running the code, it is just such a sily thing, but if it isn't saved it is read like if it was empty, or never changed.

How can I use Kivy TextInput to assign attributes to an object?

I've coded off and on as a hobby since the pandemic, and feel like I've gotten the hang of OOP and have began working on a basketball simulator. I've created a simulator uses a Player and Team class to simulate full basketball games, and now I'm looking to create a GUI using Kivy. I've watched dozens of tutorials, but I can't find anything that makes sense for what I already understand about Python.
I'd like to have a screen where the user can set attributes 1-99 for each player's offense and defense attribute using Kivy TextInput's, and have those values be assigned to each player.offense, so that when I hit "run," it runs my actual game script.
This is probably a stupid question and I just need to keep digging until I figure it out, but if anyone else had a similar mental barrier when learning Kivy, I'd love to hear how you made it make sense. Thanks!
Here is a minimal example showing how to assign a value to an attribute from a text input:
from kivy.app import App
from kivy.lang import Builder
from kivy.properties import StringProperty
from kivy.uix.textinput import TextInput
kv = '''
BoxLayout:
text: your_textinput
orientation: 'vertical'
TextInput:
id: your_textinput
Button:
text: 'click'
on_press: app.clicked()
'''
class MyApp(App):
my_attribute = StringProperty()
def build(self):
return Builder.load_string(kv)
def clicked(self):
self.my_attribute = self.root.ids.your_textinput.text
print(self.my_attribute)
if __name__ == '__main__':
MyApp().run()
Probably self.root.ids.your_textinput.text is the most important part of it.
It goes as follow:
self is MyApp class
root is the main widget inside the app which is BoxLayout in this example
ids is a dictionary containing items that you assigned in your kv language code.
your_textinput: is the id we assigned to TextInput in kv language code
text is an attribute of the TextInput where the input is stored
Sometimes it gets trick to find which is root and which ids is under what object. You can use print with dir() and __class__ to detect it.
for example:
You can find if root has an ids attribute by using dir() on root:
print(dir(self.root))
You can also know what type of class is it by using:
print(self.root.__class__)
which give:
<class 'kivy.uix.boxlayout.BoxLayout'>
You can also use __doc__ if you added proper comments to your code.
print(self.__doc__)
Gives:
Main app class
You can read more about ids here:
https://kivy.org/doc/stable/api-kivy.uix.widget.html?#kivy.uix.widget.Widget.ids
Hope this is helpful and wish you enjoyable time using Kivy.

Equivalent to `wx.CallLater()` in Kivy/KivyMD or how do deal with `time.sleep()` freezing the GUI?

I'm trying to make an app with KivyMD/Kivy, and I'd like to change a label's text multiple times with a few seconds of interval between the changes. I initially tried to do this with time.sleep(), but this froze up the GUI completely, which made the label changes and such not work.
I've seen that wxPython has the wx.CallLater() function which (if I understand correctly) will call a certain function in some amount of time without freezing up the GUI. In this thread, people were talking about threading, but it seemed to rise another problem without fixing the initial problem, so I'm really not sure if this would work in my case.
So is threading the way to go, is there an equivalent of wx.CallLater() in Kivy, or is there another better solution to my problem?
Working test code:
from kivymd.app import MDApp
from kivy.lang import Builder
import time
KV = '''
MDScreen:
MDFillRoundFlatIconButton:
id: button
icon: 'git'
on_release: app.some_func()
'''
class Test(MDApp):
def build(self):
return Builder.load_string(KV)
def some_func(self):
for i in range(3):
self.root.ids.button.text = str(3 - i)
time.sleep(3)
self.root.ids.button.text = 'Go'
Test().run()
As #John Anderson suggested, the Clock object from kivy.clock has methods that achieve the same thing as wx.CallLater().
from kivy.clock import Clock
# to schedule an event once:
Clock.schedule_once(lambda _: some_function(), in_x_seconds)
# to schedule an event repeatedly:
Clock.schedule_interval(lambda _: some_function(), every_x_seconds)

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.

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