python - 使用按钮更改类变量
问题描述
我正在尝试根据我在互联网上找到的教程(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新手
解决方案
我在相关的地方添加了评论
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
推荐阅读
- bash - 如何grep单引号之间的所有内容?
- ajax - 将 JavaScript 数组或对象发送到 Django 视图
- php - 我的 Facebook 应用需要上线吗?
- php - Symfony4 / Doctrine2 上具有可变数量标准的表格
- python-3.x - 通过迭代文件来比较不同路径中具有相同名称的两种不同文件类型
- php - 计算多维数组中的数据
- java - 在 Google Drive 文件夹中创建文件
- r - kableExtra 停止评估表中的乳胶代码
- python - 使用 Pandas 访问 Oracle 模式中的表
- regex - 如何在golang中使用正则表达式重命名json字符串中的根字段而不影响同名的内部字段?