Python / Kivy的新手,试图制作一个简单的结账系统

时间:2017-01-27 16:33:30

标签: python kivy

我的compsci课程的作业涉及制作一个简单的GUI来检查产品。我们上周刚刚开始使用Python / Kivy。我有一个问题,让我的按钮添加到总价格。

我希望这个程序要做的是当你点击一个免费汉堡的按钮时,总共加2美元。单击付费汉堡的按钮时,请为总计添加1美元。我无法让他们添加到总数中。

from kivy.app import App
from kivy.modules import inspector # For inspection.
from kivy.core.window import Window # For inspection.
from kivy.properties import NumericProperty
from kivy.properties import BooleanProperty
__app_package__ = 'edu.unl.cse.soft161.order'
__app__ = 'Order Meal'
__version__ = '0.1'
__flags__ = ['--bootstrap=sdl2', '--requirements=python2,kivy', '--orientation=landscape']


class OrderApp(App):
    total = NumericProperty(0)
    freeBurger = BooleanProperty(False)
    paidBurger = BooleanProperty(False)
    def build(self):
        inspector.create_inspector(Window, self) # For inspection (press control-e to toggle).
    def item(self, item):
        amount = NumericProperty(self.item)
        self.total = amount + self.total
    def service(self, service):
        amount = NumericProperty(self.service)
        self.total = self.total * amount

if __name__ == '__main__':
    app = OrderApp()
    app.run()

KIVY APP HERE

BoxLayout:
    orientation: 'vertical'
    BoxLayout:
        orientation: 'horizontal'
        Button:
            id: button1
            text: 'Order Free Burger'
            value: 2
            on_press: app.item(self.value)

        Button:
            id: button2
            text: 'Order Paid Burger'
            value: 1
            on_press: app.item(self.value)
    BoxLayout:
        orientation: 'horizontal'
        Button:
            id: service1
            value: 1.2
            text: 'Good service'
            on_press: app.service(self.value)
        Button:
            id: service2
            value: 1.15
            text: 'Okay service'
        Button:
            id: service3
            value: 1.1
            text: 'Bad service'
    BoxLayout:
        orientation: 'horizontal'
        Label:
            id: label1
            text: 'Meal Total:'
        Label:
            id: totalLabel
            text: str(app.total)

1 个答案:

答案 0 :(得分:1)

解决方案:

而不是你的

on_press: app.service(self.value)

在.kv文件中你可以做到

on_press: app.total += self.value

您可以安全地删除Python文件中的item - 方法。

替代解决方案:

保留.kv文件,并将item - 方法更改为

def item(self, amount):
    self.total = amount + self.total  # or shorter: self.total += amount

您的问题的解释:

在您的item - 方法版本中,您使用的是self.item,而不是名为item的参数。但是self引用了OrderApp类型的对象,因此self.item引用了名为item的方法 - 而不是此方法的参数恰好具有相同的名称。为了减少混淆的可能性,我在第二个解决方案中将参数的名称更改为amount

此外,您似乎试图在NumericProperty - 方法中定义item。不要这样做;)这样的属性声明只在类级别(在任何方法之外)进行。 (并且因为您只想在item - 方法结束之前使用参数item,所以无论如何都不需要永久保存它。)可以将参数添加到self.total没有任何转变。

如果您再次面临类似问题,可能需要在代码中添加一些print语句。这使您可以在应用程序崩溃之前查看变量的状态。这种技术的一个例子是

def item(self, item):
    print "*" * 300  # prints 300 asterisks so you can find it quickly
    print self.item  # shows that self.item is a method and *not* the argument
    # ... more code ...

玩得开心! :)

相关问题