登录系统; 我有一个错误。如何在txt1中获取文本以及如何通过按钮更改?
文件“/home/hypermesh/Desktop/main.py”,第11行,在messageShow中 if self.txt1.text ==“stock”: AttributeError:'Button'对象没有属性'txt1'
#-*- coding: utf-8 -*-
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.uix.textinput import TextInput
from kivy.uix.gridlayout import GridLayout
from kivy.uix.widget import Widget
def messageShow(self):
if self.txt1.text == "stock":
pop=Popup(text="yes")
else:
pop=Popup(text="error")
class SimpleKivy(App):
def build(self):
grid=GridLayout(rows=3, cols=2)
lbl1=Label(text="ID :",italic=True, bold=True)
lbl2=Label(text="Password :",italic=True, bold=True)
txt1=TextInput(multiline=False, font_size=50)
txt2=TextInput(multiline=False, password=True)
btn1=Button(text="Exit",italic=True)
btn2=Button(text="OK",italic=True)
btn2.bind(on_press=messageShow)
grid.add_widget(lbl1)
grid.add_widget(txt1)
grid.add_widget(lbl2)
grid.add_widget(txt2)
grid.add_widget(btn1)
grid.add_widget(btn2)
return grid
if __name__ == "__main__":
SimpleKivy().run()
答案 0 :(得分:1)
你做对了......但你必须保存一个你想稍后访问的anthing的引用(通常将它附加到自己)
def __init__(...):
...
self.txt1=TextInput(multiline=False, font_size=50)
...
那么你的其他函数应该可以正常工作(除了方法应该是类的一部分..)
class SimpleKivy(App):
def messageShow(self,evt):
if self.txt1.text == "stock":
pop=Popup(text="yes")
else:
pop=Popup(text="error")
def build(self):
grid=GridLayout(rows=3, cols=2)
lbl1=Label(text="ID :",italic=True, bold=True)
另一种选择是使用lambdas来调用它
def messageShow(message):
print "GOT MESSAGE:",message
class SimpleKivy(App):
def __init__(self,...):
txt1 = TextInput(...)
...
btn.bind(on_press=lambda *a:messageShow(txt1.text))
在这种情况下,txt1位于变量范围内,并且能够将其字符串传递给messageShow
答案 1 :(得分:0)
这段代码工作:)
def messageShow(message):
if message == "stock":
btn3=Button(text='Close me!')
pop=Popup(content=btn3, title='Information Message !')
pop.open()
btn3.bind(on_press=pop.dismiss)
else:
btn3=Button(text='Exit')
pop=Popup(content=btn3, title='Information Message !')
pop.open()
btn3.bind(on_press=pop.dismiss)
class LoginScreen(GridLayout):
def __init__(self):
super(LoginScreen, self).__init__()
self.rows=3
self.cols=2
lbl1=Label(text="ID :",italic=True, bold=True)
lbl2=Label(text="Password :",italic=True, bold=True)
txt1=TextInput(multiline=False, font_size=50)
txt2=TextInput(multiline=False, password=True)
btn1=Button(text="Exit",italic=True)
btn2=Button(text="OK",italic=True)
btn2.bind(on_press=lambda *a:messageShow(txt1.text))
self.add_widget(lbl1)
self.add_widget(txt1)
self.add_widget(lbl2)
self.add_widget(txt2)
self.add_widget(btn1)
self.add_widget(btn2)
class SimpleKivy(App):
def build(self):
return LoginScreen()
if __name__ == "__main__":
SimpleKivy().run()