提问人:Brian Tomasetti 提问时间:9/6/2023 更新时间:9/6/2023 访问量:38
在 Python 中将值从方法中提取到其他类中
Pulling values form methods into other classes in Python
问:
我正在用 Kivy 编写一个 Python 脚本。截至目前,该应用程序按预期工作。除了我遇到了障碍,无法找到解决方案。在“class Output(screen)”类中,我想从“Class Cost(Screen)”和“Class Tip(Screen)”类中提取从屏幕输入生成的值。现在,在编写代码时,来自屏幕的输入被拉入相应的类(Cost 和 Tip)中,并用 Python 打印。所以,我知道这个逻辑是有效的。我需要一种方法在类 Output(Screen) 中调用这些值。提前感谢您的任何建议。
import kivy
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import ObjectProperty
class Cost(Screen):
cost = ObjectProperty(None)
def btn(self):
cost = self.ids.cost.text
print(cost)
class Tip(Screen):
tip = ObjectProperty(None)
def btn(self):
tip = self.ids.tip.text
print(tip)
class Output(Screen):
pass
class WindowManager(ScreenManager):
pass
kv = Builder.load_file("att.kv")
class ATT(App):
def build(self):
return kv
if __name__ == "__main__":
ATT().run()
type here
att.kv 文件
<Label>:
color:0.5,0.5,0.5,1
font_size:30
<Button>:
background_color: 0, 0, 3, .6
color:1.0,1.0,1.0,1
font_size:20
markup: True
WindowManager
Cost:
Tip:
Output:
<Cost>
name: "Cost"
cost: cost
Label:
size_hint:{0.3, 0.2}
pos_hint: {"x":0.20, "y":0.5}
color:1.0,1.0,1.0,1
text: "What's the Total Bill? $"
TextInput:
focus: "True"
id: cost
size_hint:{0.2, 0.1}
pos_hint: {"x":0.58, "y":0.55}
multiline:False
input_filter: "float"
Button:
size_hint:{0.2, 0.1}
pos_hint: {"x":0.4, "y":0.2}
text: "[b]Next[/b]"
on_press: root.btn()
on_release:
app.root.current = "Tip"
root.manager.transition.direction = "left"
<Tip>
name: "Tip"
tip: tip
Label:
size_hint:{0.3, 0.2}
pos_hint: {"x":0.24, "y":0.5}
color:1.0,1.0,1.0,1
text: "Tip Percentage? %"
TextInput:
id: tip
size_hint:{0.2, 0.1}
pos_hint: {"x":0.58, "y":0.55}
multiline:False
input_filter: "float"
Button:
size_hint:{0.2, 0.1}
pos_hint: {"x":0.5, "y":0.2}
text: "[b]Next[/b]"
on_press: root.btn()
on_release:
app.root.current = "Output"
root.manager.transition.direction = "left"
Button:
size_hint:{0.2, 0.1}
pos_hint: {"x":0.27, "y":0.2}
text: "[b]Back[/b]"
on_release:
app.root.current = "Cost"
root.manager.transition.direction = "right"
<Output>
name: "Output"
Label:
size_hint:{0.3, 0.2}
pos_hint: {"x":0.20, "y":0.5}
color:1.0,1.0,1.0,1
text: "Output"
Button:
size_hint:{0.2, 0.1}
pos_hint: {"x":0.5, "y":0.2}
text: "[b]Close[/b]"
on_press: app.stop()
Button:
size_hint:{0.2, 0.1}
pos_hint: {"x":0.27, "y":0.2}
text: "[b]Start Over[/b]"
on_press:
app.root.current = "Cost"
root.manager.transition.direction = "right"
答:
0赞
John Anderson
9/6/2023
#1
如果将 添加到类中:id
Output
<Output>
name: "Output"
Label:
id: output
size_hint:{0.3, 0.2}
然后,您可以向类中添加一个方法:on_enter()
Output
class Output(Screen):
def on_enter(self, *args):
self.ids.output.text = 'Cost: ' + self.manager.get_screen('Cost').ids.cost.text + ' Tip: ' + self.manager.get_screen('Tip').ids.tip.text
显然,您可以调整上面的代码来执行所需的任何计算。
评论
0赞
Brian Tomasetti
9/7/2023
是的,这奏效了,谢谢安德森@John
评论