Python 使用按钮更改类变量
我正试图根据在internet上找到的教程()构建一个简单的计算器。我试图重建他的代码,但只使用纯phython,而不是kv文件。这是我目前的代码:Python 使用按钮更改类变量,python,python-3.x,user-interface,kivy,Python,Python 3.x,User Interface,Kivy,我正试图根据在internet上找到的教程()构建一个简单的计算器。我试图重建他的代码,但只使用纯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
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
解决方案-App.get_running_App().root
使用App.get_running_App().root
获取根的实例并访问类属性、方法和WDIGET
片段
输出
再问一个问题。无法访问“Window.entry.text=x”中其他类的属性是否正常?您是否总是必须在类本身内部才能更改其属性?
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