Python / Kivy立即崩溃

时间:2019-01-17 09:43:21

标签: python python-3.x canvas kivy

总体问题是:为什么我的Kivy应用程序立即崩溃?

我的 Python 代码是:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
from kivy.graphics import Line

class MainScreen(Screen):
    pass

class AnotherScreen(Screen):
    pass

class ScreenManagement(ScreenManager):
    pass

class TouchInput(Widget):
    def on_touch_down(self, touch):
        with self.canvas:
            touch.ud["line"] = Line(points=(touch.x, touch.y))
    def on_touch_move(self, touch):
        touch.ud["line"].points += (touch.x, touch.y)

presentation = Builder.load_file("simplekivy.kv")

class SimpleKivy(App):
    def build(self):
        return presentation

if  __name__ == "__main__":
    SimpleKivy().run()

我的 Kv。代码是:

#: import FadeTransition kivy.uix.screenmanager.FadeTransition

ScreenManagement:
    transition: FadeTransition()
    MainScreen:
    AnotherScreen:

<MainScreen>:
    name: "Main"
    Button:
        on_release: app.root.current = "Other"
        text: "Next screen!"
        font_size: 50

<AnotherScreen>:
    name: "Other"
    FloatLayout:
        TouchInput:
            id: touch
        Button:
            on_release: app.root.current = "Main"
            text: "Going back!"
            font_size: 40
            color: 0,1,0,1
            size_hint: 0.3, 0.2
            pos_hint: {'right': 1, 'top': 1}

        Button:
            on_release: touch.canvas.clear()
            text: "Clear window"
            font_size: 40
            color: 0,1,0,1
            size_hint: 0.3, 0.2
            pos_hint: {'right': 1, 'top': 0}

当我删除“清除窗口”按钮时,该应用程序将按预期工作。但是,添加按钮后,它立即崩溃并显示错误消息

  

Python已停止工作

1 个答案:

答案 0 :(得分:1)

当您使用python编写代码并使用kv时,库本身将在与.py文件相同的目录中查找.kv文件,因此您不必以'presentation = Builder.load_file(“ simplekivy。kv“)'

这可以解决,将python代码更改为:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
from kivy.graphics import Line

class MainScreen(Screen):
    pass

class AnotherScreen(Screen):
    pass

class ScreenManagement(ScreenManager):
    pass

class TouchInput(Widget):
    def on_touch_down(self, touch):
        with self.canvas:
            touch.ud["line"] = Line(points=(touch.x, touch.y))
    def on_touch_move(self, touch):
        touch.ud["line"].points += (touch.x, touch.y)
#don't need this
#presentation = Builder.load_file("simplekivy.kv")

class SimpleKivy(App):
    pass
    #I commented on that part of your code and added a 'pass' above
    #def build(self):
    #    return presentation

if  __name__ == "__main__":
    SimpleKivy().run()