python:来自类内的函数调用

时间:2017-12-10 17:04:41

标签: python kivy

这是一个展示" Hello"的示例程序。或者"再见"当你按下按钮1或2时,简化了我的真实程序。
我想要做的是执行函数btn1()并显示" Hello"程序启动时,无需按下按钮1 什么行代码以及我应该在哪里添加?
当我把" Greetings()。btn1()"在课堂上问候,错误:"姓名问候未定义"发生。然后我在类StudentApp中的def build(self)之后放了相同的命令,但什么都没发生。

在main.py中,

from kivy.app import App  
from kivy.uix.boxlayout import BoxLayout  
from kivy.properties import StringProperty  

class Greetings(BoxLayout):
    greeting=StringProperty()  

    def btn1(self):  
        self.greeting='Hello.'  

    def btn2(self):  
        self.greeting='Good-bye.'  

class GreetingApp(App):  
    def build(self):  
        return Greetings()  

GreetingApp().run()  

在greeting.kv中,

#: import main main

Greetings:  
<Greetings>:

    orientation: "vertical"  
    Label:  
        text: root.greeting  
    BoxLayout:  
        orientation: "horizontal"  
        Button:  
            text: '1'  
            on_press: root.btn1()  
        Button:  
            text: '2'  
            on_press: root.btn2()  

2 个答案:

答案 0 :(得分:0)

在返回根窗口小部件之前调用btn1

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty
from kivy.lang import Builder


Builder.load_string('''
<Greetings>:
    orientation: "vertical"

    Label:
        text: root.greeting
    BoxLayout:
        orientation: "horizontal"

        Button:
            text: '1'
            on_press: root.btn1()
        Button:
            text: '2'
            on_press: root.btn2()
''')


class Greetings(BoxLayout):
    greeting = StringProperty()

    def btn1(self):
        self.greeting = 'Hello.' 

    def btn2(self): 
        self.greeting = 'Good-bye.' 

class GreetingApp(App):
    def build(self):
        root = Greetings()
        root.btn1()

        return root

GreetingApp().run()

答案 1 :(得分:0)

每次创建类的实例时都会运行__init__方法 那么你想在对象的创建时间做什么,你可以放入__init__。启动对象。
把它放在你的Greetings课程中。

def __init__(self, **kwargs):
    super(Greetings, self).__init__(**kwargs)
    self.btn1()

然后在创建对象时调用它。