我有如下所示的代码。在函数填充中,我有变量fro,to和transport。我试图将这些变量调用到get函数中,然后在显示Popup时调用它们。然后,这些变量将显示在弹出窗口中。但是,我有一个NameError:名称'fro'没有用我的代码定义。当我使用num = Connected.get()
代替num = g
并注释掉c =Connected()
和g= c.get()
时,我会在MessageBox Popup中显示&lt; bound method MessageBox.get of <connected.MessageBox object at 0x000000000B36F3F0>>
。我不知道是什么我做错了。有没有更好的方法呢?
class Connected(Screen):
def populate(self, transText, beginText, toText):
global fro
global to
global transport
self.rv.data = []
self.ids.results.text=""
self.ids.no_entry.text=""
fro = beginText
to = toText
transport = transText
def get(self):
b = fro
a = StringProperty(b)
return a
class MessageBox(Popup):
c = Connected()
g = c.get()
route = 'MessageBox'
num = g
#num = Connected.get()
def popup_dismiss(self):
self.dismiss()
Kivy.kv
<MessageBox>:
title: root.route
size_hint: None, None
size: 400, 400
separator_color: 1,0,0,1
BoxLayout:
orientation: 'vertical'
Label:
id: info
#text: 'nice'
text: str(root.num)
Button:
size_hint: 1, 0.2
text: 'OK'
on_press:
root.dismiss()
答案 0 :(得分:1)
必须在导入后置证后定义全局变量。导入因为我没有完整的代码。以下示例只是一个例子。
from kivy.app import App
from kivy.uix.screenmanager import Screen
from kivy.uix.popup import Popup
from kivy.properties import StringProperty
fro = "fro-1-2-3"
to = "to-1-2-3"
transport = "transport-1-2-3"
class Connected(Screen):
def __init__(self, **kwargs):
super(Connected, self).__init__(**kwargs)
self.populate("transText", "beginText", "toText")
def populate(self, transText, beginText, toText):
global fro
global to
global transport
# self.rv.data = []
# self.ids.results.text = ""
# self.ids.no_entry.text = ""
fro = beginText
to = toText
transport = transText
def get(self):
print("Connected.get: from={}".format(fro))
b = fro
a = StringProperty(b)
return a
class MessageBox(Popup):
c = Connected()
g = c.get()
print("MessageBox: g={}".format(g))
route = 'MessageBox'
num = g
#num = Connected.get()
def popup_dismiss(self):
self.dismiss()
class TestApp(App):
def build(self):
return MessageBox()
if __name__ == "__main__":
TestApp().run()
#:kivy 1.10.0
<Connected>:
<MessageBox>:
title: root.route
size_hint: None, None
size: 400, 400
separator_color: 1,0,0,1
BoxLayout:
orientation: 'vertical'
Label:
id: info
#text: 'nice'
text: str(root.num)
Button:
size_hint: 1, 0.2
text: 'OK'
on_press:
root.dismiss()