【发布时间】:2020-01-31 00:08:37
【问题描述】:
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
import json
import re
class Grid(GridLayout):
def __init__(self, **kwargs):
super(Grid, self).__init__(**kwargs)
# Columns for the main view
self.cols = 1
# Start of the Inside
self.inside = GridLayout()
self.inside.rows = 3
self.inside.add_widget(Label(text = 'Enter the Brand Name for its Products: '))
self.brand_input = TextInput(multiline = False)
self.inside.add_widget(self.brand_input)
# Add the things in inside to the main
self.add_widget(self.inside)
self.submit = Button(text = 'Submit', font_size = 20)
self.submit.bind(on_press = self.pressed)
self.add_widget(self.submit)
def pressed(self, instance):
# Pull the text inside the textInput
brand_name = self.brand_input.text
with open('mcg_app/brands.json', 'r') as f:
brands_dict = json.load(f)
request = brands_dict[brand_name]
modified_result = re.sub(r',\s(?![^(]*\))', "\n", str(request))
self.inside.add_widget(Label(text = modified_result))
# Clear out the fields after submitting
self.brand_input.text = ''
class Mcg(App):
def build(self):
return Grid()
if __name__ == '__main__':
Mcg().run()
你好,这里的程序有一个文本输入框,用户输入一个品牌名称,例如“Dove”,然后他按下提交按钮,按钮连接到pressed()函数。该程序的一切实际上都运行良好,唯一的问题是在我打印输入品牌的产品之后,假设他输入了不同的品牌,在这种情况下,旧的输出仍然存在,所以程序输出的新产品已经存在旧产品。我怎样才能解决这个问题?提前致谢
【问题讨论】:
-
你能提供一个示例json吗?没有一个应用程序就无法运行..
-
只保留对包含结果的
Label的引用。然后你可以只替换它的text,而不是每次都创建一个新的Label。
标签: python kivy kivy-language