使用按钮更改类变量

时间:2018-07-10 00:04:53

标签: python python-3.x user-interface kivy

我正在尝试根据我在互联网(http://www.newthinktank.com/2016/10/kivy-tutorial-3/)上找到的教程来构建一个简单的计算器。我正在尝试重建他的代码,但仅使用纯phython,而不是kv文件。到目前为止,这是我的代码:

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput

class Window(GridLayout):
    def __init__(self,**kwargs):
        super(Window,self).__init__(**kwargs)
        self.rows=5
        self.padding=10
        self.spacing=10
        self.entry=TextInput(font_size=32)
        self.add_widget(self.entry)
        self.add_widget(Box1())


class Box1(BoxLayout):
    def __init__(self,**kwargs):
        super().__init__(orientation='horizontal',**kwargs)
        self.add_widget(CustButton(text='Hi'))


class CustButton(Button):
    def __init__(self,**kwargs):
        super(CustButton,self).__init__(font_size=32,**kwargs)
    def on_press(self):
        self.entry.text=self.text


class Calculator(App):
    def build(self):
        return Window()

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

问题是我不断收到此错误消息:“ AttributeError:'CustButton'对象没有属性'entry'”

我尝试了很多事情,却无法完成!!那么,如何通过按钮更改“ Window.entry”的文本?

非常感谢python新手

2 个答案:

答案 0 :(得分:0)

我已经在相对位置添加了评论

class Window(GridLayout):
    def __init__(self,**kwargs):
        super(Window,self).__init__(**kwargs)
        self.rows=5
        self.padding=10
        self.spacing=10
        self.entry=TextInput(font_size=32)
        self.add_widget(self.entry)
        self.box1 = Box1() # save box1 as an instance attribute
        self.add_widget(self.box1)
        # bind your on_press here ... where you can access the self.entry
        self.box1.button.bind(on_press=self.on_press)
    def on_press(self,target):
        self.entry.text=target.text


class Box1(BoxLayout):
    def __init__(self,**kwargs):
        super().__init__(orientation='horizontal',**kwargs)
        self.button = CustButton(text='Hi') # save an instance to our class
        self.add_widget(self.button)


class CustButton(Button):
    def __init__(self,**kwargs):
        super(CustButton,self).__init__(font_size=32,**kwargs)
    # def on_press(self):
    #    pass # self.entry.text=self.text

答案 1 :(得分:0)

解决方案-App.get_running_app()。root

使用App.get_running_app().root获取根的实例并访问类的属性,方法和wdigets。

摘要

class CustButton(Button):
    def __init__(self, **kwargs):
        super(CustButton, self).__init__(font_size=32, **kwargs)

    def on_press(self):
        App.get_running_app().root.entry.text = self.text

输出

Img01