Python将属性从其他类获取到另一个类

时间:2017-12-24 08:16:56

标签: python python-3.x kivy kivy-language

在Python中构建应用程序相当新,我无法弄清楚如何将参数从其他类函数传递到其他类。基于我读到的内容,我想我应该在CustomPopup类中使用def init 但是无法使其正常工作。

这是我正在尝试做的一个剥离版本,这有效,但我试图从popuper获取txt_input到CustomPopup但无法使其工作:

的Python:

from kivy.app import App
from kivy.lang import Builder
from os import listdir
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.uix.popup import Popup
import teradata
import Global

class CustomPopup(Popup):
    txt_input = 'Text'

udaExec = teradata.UdaExec()

kv_path = './kv/'
for kv in listdir(kv_path):
    Builder.load_file(kv_path+kv)

class LoginScreen(Screen):

    def buttonClicked(self):
        Global.u_name = self.ids.u_name.text
        Global.p_word = self.ids.p_word.text
        status = None
        try:
            with udaExec.connect("${dataSourceName}",username=self.ids.u_name.text,password=self.ids.p_word.text) as session:
                try:
                    session
                except teradata.DatabaseError as e:
                    status = e.code
        except teradata.DatabaseError as e:
            status = e.code

        if status == 8017:
            self.popuper('Hello')
        elif status == None:
            self.popuper('All Good')
        elif status == 0:
            self.popuper('Fill in username')
        else:
            self.popuper('Something else')

    def popuper(self, txt_input):
        popuper = CustomPopup()
        popuper.open()

class MainScreen(Screen):
    pass

class ScreenManagement(ScreenManager):
    pass

application = Builder.load_file("main.kv")

class MainApp(App):

    def build(self):
        self.title = 'Push Notfication Tool'
        return application

if __name__ == "__main__":
    MainApp().run()

Kivy:

<CustomPopup@Popup>:
    size_hint: (.5,.5)
    auto_dismiss: False
    title: "af"
    BoxLayout:
        orientation: 'vertical'
        Label:
            text: root.txt_input
        Button:
            text: "Close now"
            on_press: root.dismiss()

谢谢!

* EDIT也添加了kivy文件。

1 个答案:

答案 0 :(得分:0)

尝试更改一些内容:

class CustomPopup(Popup):
    txt_input = StringProperty('Text')

    def __init__(self, txt_input, **kw): 
         super().__init__(**kw)
         self.txt_input = txt_input

...
    def popuper(self, txt_input):
        popuper = CustomPopup(txt_input) # send txt_input!
        popuper.open()

现在是kv文件

<CustomPopup>: # removed @Popup since you created it in python...
    size_hint: (.5,.5)
    auto_dismiss: False
    title: "af"
    BoxLayout:
        orientation: 'vertical'
        Label:
            text: root.txt_input
        Button:
            text: "Close now"
            on_press: root.dismiss()