首页 > 解决方案 > 使用按钮更改类变量

问题描述

我正在尝试根据我在互联网上找到的教程(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新手

标签: pythonpython-3.xuser-interfacekivy

解决方案


我在相关的地方添加了评论

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

推荐阅读