0

我是 python 的新手,现在用kivy. 问题是当我输入文本时,它不起作用。在下面我只想检查它是否工作,所以我放了一些弹出窗口,如果输入文本是'a'print true。只是检查它是否工作,希望你们帮助我,谢谢。

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.lang import Builder
from kivy.uix.popup import Popup
from kivy.uix.bubble import Bubble

class CustomPopup(Popup):
    pass

class Diction(GridLayout):

    def __init__(self, **kwargs):
        super(Diction, self).__init__(**kwargs)
        self.cols=2
        self.add_widget(Label(text="Search"))
        self.search=TextInput(multiline=False)
        self.add_widget(self.search)
        if self.search=='A':
            print 'True'
        else:
            print 'False'
        self.add_widget(Button(text="click",on_press=self.show_popup))
    def show_popup(self, b):
        p = CustomPopup()
        p.open()

class MyApp(App):
    def build(self):
        return LoginScreen()

if __name__=="__main__":
    MyApp().run()
4

1 回答 1

0

不工作的原因有两个:

  1. if应该在处理事件的方法中,即show_popup
  2. 您应该比较text中的Label,而不是Label本身。而不是self.search=='A',您应该使用self.search.text=='A'

这是更正后的__init__代码show_popup

class Diction(GridLayout):

    def __init__(self, **kwargs):
        super(Diction, self).__init__(**kwargs)
        self.cols=2
        self.add_widget(Label(text="Search"))
        self.search=TextInput(multiline=False)
        self.add_widget(self.search)
        self.add_widget(Button(text="click",on_press=self.show_popup))

    def show_popup(self, b):
        if self.search.text=='A':
            print 'True'
        else:
            print 'False'
        p = CustomPopup()
        p.open()

使用 Kivy 语言的另一种方法

Kivy 语言可以帮助您拥有更简洁的代码。您的代码可能如下所示:

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
# DON'T forget to import Label!!!
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.lang import Builder

Builder.load_string("""
<CustomPopup@Popup>:
    title: "My Custom Poput"    

<Diction@GridLayout>:
    cols: 2
    search: id_search
    Label:
        text: "Search"
    TextInput:
        id: id_search
    Button:
        text: "click"
        on_press: root.show_popup(self)
""")

class CustomPopup(Popup):
    pass

class Diction(GridLayout):    
    def show_popup(self, b):
        if self.search.text=='A':
            print 'True'
        else:
            print 'False'
    # You can send any content to the popup with the content attribute
    CustomPopup(content=Label(text=self.search.text)).open()

class MyApp(App):
    def build(self):
        return Diction()

它有助于保持逻辑与界面分离。如果您使用该load_file功能而不是load_string.

于 2013-11-03T19:21:35.207 回答