首页 > 解决方案 > Kivy on_press 声明后数据无效

问题描述

我正在尝试使用 floatlayout 向我的 Kivy 应用程序添加 2 个按钮并进行 on_press 调用。当我尝试运行它时,我得到一个错误:第 12 行声明后无效数据

我的 main.py

import kivy

from kivy.app import App
from kivy.uix.widget import Widget 
import __init__ as hvn


class HVNLayout(Widget): 
    def optBtn(self):
       print("hello") 

    def genBtn(self):
        print("Bye")
  
class HVNApp(App):
    def build(self):
        return HVNLayout() 


  
if __name__ == '__main__':
    HVNApp().run()

和.kv

<HVNLayout>:
    canvas.before:
        Rectangle:
            size: self.size
            source: "images/dice.jpg"

    FloatLayout:
        size: root.width, root.height

        Button:
            text: "Option"
            on_press: root.btn()
            pos_hint: {"top": 1, "right": 1}
            size_hint: (None, None)
            size: 200, 100

        Button:
            text: "Generate"
            post_hint: {"x": 0.15, "y": 0.1}
            size_hint: (None, None)
            size: 200, 100

标签: pythonkivykivy-language

解决方案


您的 kv 文件的缩进不正确。它应该是:

<HVNLayout>:
    canvas.before:
        Rectangle:
            size: self.size
            source: "images/dice.jpg"

    FloatLayout:
        size: root.width, root.height

        Button:
            text: "Option"
            on_press: root.btn()
            pos_hint: {"top": 1, "right": 1}
            size_hint: (None, None)
            size: 200, 100

    Button:
        text: "Generate"
        post_hint: {"x": 0.15, "y": 0.1}
        size_hint: (None, None)
        size: 200, 100

推荐阅读