简体   繁体   English

如何在Python3中使用Kivy绘制一条简单的线和一个矩形?

[英]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. 我只是想让程序使用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. 我是Python的新手,还是Kivy的新手,而我以前从未使用过GUI。 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. 我希望12是矩形的位置,6是矩形的大小,但是会打印出错误消息“未定义名称'self'”。 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. 我也很喜欢,如果有某种方式可以使用.kv文件解决我的问题,那么我只会使用.py文件,因为.kv也不适合我。

In the first lines of your definition you have 在定义的第一行中

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

and self does not exist there; 那里不存在self in order to initialize those values you have to do: 为了初始化这些值,您必须执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM