我有下面显示的代码。 在填充的函数中,我有变量fro,to和transport。 我试图将这些变量调用到get函数中,然后在显示弹出窗口时调用它们。 这些变量将显示在弹出窗口中。 但是,我遇到了NameError:我的代码未定义名称" fro"。 当我使用num = Connected.get()而不是num = g并注释掉c =Connected()和g= c.get()时,我在消息框弹出窗口中显示了bound method MessageBox.get of >。我不知道我在做什么错。 有更好的方法吗?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32class 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17:
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()
在def get(self)中未定义变量fro,因此它失败。 也许您忘了在该方法中添加global fro?
我也尝试过。 它仍然给我一个错误。 但是,如果我没有在get函数中调用get()函数和print(fro),它将正常工作。
正如我所说的,如果您从未定义fro,它将不起作用。
我假设您已经在Python脚本的顶部定义了变量" fro"," to"和" transport",即在所有import语句之后。
全局变量必须在导入后声明之后定义。 导入由于我没有您的完整代码。 以下示例仅是一个示例。
例
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58from 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()
测试文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21#:kivy 1.10.0
:
:
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()
输出量