Обновление ярлыка kivy на экране при динамическом создании его через список? - PullRequest
0 голосов
/ 21 ноября 2018

Во-первых, отказ от ответственности: я ужасно новичок в программировании и пытаюсь построить мое понимание с этим проектом.Кроме того, позвольте мне сказать, что я искал форумы и нашел похожие посты, но у меня нет проблем с обновлением метки, которая была сгенерирована динамически через список.

Мой вопрос в моем коде, закомментированПодводя итог: я генерирую кнопки и метки для каждого элемента в списке.Затем кнопки должны складываться и вычитаться из связанного значения в словаре.В настоящее время код делает это, но метки на экране не обновляются, чтобы отражать новые значения.Может ли кто-нибудь помочь с обновлением значения "ordlayout.add_widget (ordlayout.lbl [str (i)])" при обращении к updateup и updatedown?

import kivy
kivy.require('1.10.0')
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.gridlayout import GridLayout
from kivy.uix.scrollview import ScrollView
from kivy.uix.textinput import TextInput
from kivy.lang import Builder
from kivy.uix.dropdown import DropDown
from kivy.base import runTouchApp
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from functools import partial
#The first screen the app opens to. Contains all other screen branches.
class MainScreen(Screen):
    pass

#NewOrder will be the screen used for choosing which
#items/and how many of each the customer wants added.
class NewOrder(Screen):
    def __init__(self, **kwargs):
        super(NewOrder, self).__init__(**kwargs)
        #This will eventually read/create a list of strings from a user-modified file.
        self.foods = ["Puppy", "Cat", "Fish"]
        #I create a dictionary linking a number to each item.
        self.countfoods = {}
        for i in self.foods:
            self.countfoods[i] = 0
        #Now I create a grid layout to put on the screen.
        ordlayout = GridLayout()
        ordlayout.cols = 8
        ordlayout.row_default_height=20
        ordlayout.buttons={}
        ordlayout.btns1 = {}
        ordlayout.lbl = {}
        #The items I want on the screen are 1.)First item from list. 2.) Minus button.
        #3.) Current number of the item. 4.) Plus button.
        #I want these four buttons for each item.
        for i in self.countfoods:
            #Adds text for first item.
            ordlayout.add_widget(Label(text=i))
            #Adds a button for minus, linked to a unique dict value.
            ordlayout.buttons[str(i)] = Button(text="-")
            ordlayout.lbl[str(i)] = Label(text=str((self.countfoods[i])))
            #The below assigns the specific object location of each label
            #to a variable for passing to ocuntup and countdown.
            tempPlacement = str(ordlayout.lbl[str(i)])
            ordlayout.buttons[str(i)].bind(on_press=partial(self.updatedown, i))
            ordlayout.add_widget(ordlayout.buttons[str(i)])
            #Add the value that I want to update.
            ordlayout.add_widget(ordlayout.lbl[str(i)])
            #Adds a button for addition, but doesn't properly link it to a specific value.
            ordlayout.btns1[str(i)] = Button(text="+")
            ordlayout.btns1[str(i)].bind(on_press=partial(self.updateup, i))
            ordlayout.add_widget(ordlayout.btns1[str(i)])
        #Add that grid wit
            h values to the screen.
        self.add_widget(ordlayout)

    #Function used to change value down by one.
    def updatedown(self, event, i):
        self.countfoods[event] -= 1
        print (self.countfoods)

    #Function used to change value up by one.
    def updateup(self, event, i):
        self.countfoods[event] += 1
        print (self.countfoods)


#AdminOpt will be the screen used for
class AdminOpt(Screen):
    def __init__(self, **kwargs):
        super(AdminOpt, self).__init__(**kwargs)

#Will allow for opening and checking of created orders.
class OrdHist(Screen):
    pass

#This is purely the class used for managing the other screens.
class ScreenManagement(ScreenManager):
    pass


Main = Builder.load_file("Order Handler2.kv")


class Customer:
    def __init__(self, name, pricelist):
        self.name = name
        self.pricelist = pricelist


class SimpleKivy(App):
    def build(self):
        return Main


if __name__== "__main__":
    SimpleKivy().run()

1 Ответ

0 голосов
/ 27 ноября 2018

Не удалось проверить это (в вашем вопросе отсутствует файл kv), но что-то вроде этого может сработать:

#Function used to change value down by one.
def updatedown(self, i, button):
    self.countfoods[i] -= 1
    self.ordlayout.lbl[str(i)].text = str(self.countfoods[i])
    print (self.countfoods)

#Function used to change value up by one.
def updateup(self, i, button):
    self.countfoods[i] += 1
    self.ordlayout.lbl[str(i)].text = str(self.countfoods[i])
    print (self.countfoods)

Вам также необходимо будет заменить каждый раз ordlayout с self.ordlayout в методе __init__().

Кроме того, вам не нужно делать str(i) для словарных ключей.На самом деле, вы можете использовать списки вместо словарей, если хотите.

...