【发布时间】:2020-05-26 00:32:28
【问题描述】:
我是 Kivy 的新手,需要您的帮助。我有一个小问题:
我需要一个动态数组,用户可以在第一个 TextInput 字段中输入第一个值,然后他可以按“换行”按钮,他有机会在新的 TextInput 字段中输入第二个值他可以再次按下“新行”按钮,他可以选择在新的 TextInput 字段中输入第三个值。使用“结果”,他可以随时在标签中调用这些值的总和
如何创建这个动态数组?非常感谢
这是我的 main.py 文件
from kivy.clock import Clock
from kivy.uix.textinput import TextInput
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import ObjectProperty
Builder.load_file('MyMain.kv')
class WindowManager(ScreenManager):
pass
class MainWindow(Screen):
def __init__(self, **kwargs):
super(MainWindow, self).__init__(**kwargs)
self.counter = 1
Clock.schedule_once(self.add_stuff)
def add_stuff(self, *args):
self.textlist = [TextInput()]
self.ids.grid.add_widget(Label(text='Input value {}'.format(self.counter)))
self.counter += 1
self.ids.grid.add_widget(self.textlist[0])
# function to create new inputs, that button 'new line' calls:
def addnewtextinput(self):
self.ids.grid.add_widget(Label(text='Input value ' + str(self.counter)))
self.counter += 1
self.textlist.append(TextInput())
self.ids.grid.add_widget(self.textlist[-1])
# function to get a result:
def getresult(self):
result = 0
for i in self.textlist:
# you may convert it to float if you need, like float(i.text)
result += int(i.text)
self.ids.label_id.text = str(result)
class MyMainApp(App):
def build(self):
b1=WindowManager()
MainWindow()
return b1
if __name__ == "__main__":
MyMainApp().run()
这是 MyMain.kv
<CustButton@Button>:
font_size: 40
<WindowManager>:
MainWindow:
<MainWindow>:
name: "main"
# don't forget to add this
grid: grid.__self__
GridLayout:
cols:1
# you will control that GridLayout from .py so here it's empty
GridLayout:
# set the id to be able to control it from .py file
id: grid
cols: 2
CustButton:
text: "new line"
on_press: root.addnewtextinput()
CustButton:
text: "result"
font_size: "30sp"
on_press: root.getresult()
TextInput:
id:label_id
font_size: 40
multiline: True
我看不到 kivy Window .. 你能帮帮我吗?
【问题讨论】:
标签: python arrays dynamic kivy screen