Spacepiratehacker54
Spacepiratehacker54

Reputation: 55

How do I draw a simple line and a rectangle using Kivy in Python3?

I simply want to let the program draw a line and a rectangle in a window using Kivy. Position and properties don't matter for now.

I'm new to Python and very new to Kivy und I've never worked with a GUI before. I tried searching on multiple websites but none seemed to have a solution for my problem.

import kivy
kivy.require('1.10.1')
from kivy.app import App
from kivy.uix.button import Label

class KivyTest(App):
    self.pos = 12
    self.size = 6

    def build(self):
        with self.canvas:
            Line(points=(0, 1, 2, 3, 4, 5))
            Color(1, 0, 0, .5, mode='rgba')
            Rectangle(pos=self.pos, size=self.size)

KivyTest = KivyTest()
KivyTest.run()

I expect 12 to be the position of the rectangle and 6 its size, but the error message "name 'self' is not defined" is printed out. There's obviously something crucial I don't understand. I'd also love it, if there is someway to use a .kv file for my problem, I'm only using a .py file, since .kv didn't work for me either.

Upvotes: 4

Views: 5040

Answers (1)

Tordek
Tordek

Reputation: 10872

In the first lines of your definition you have

class KivyTest(App):
    self.pos = 12
    self.size = 6

and self does not exist there; in order to initialize those values you have to do:

class KivyTest(App):
    def __init__(self):
        self.pos = 12
        self.size = 6

Upvotes: 1

Related Questions