【问题标题】:How to change value of a variable with a button press in Kivy如何在 Kivy 中按下按钮更改变量的值
【发布时间】:2021-02-12 00:27:36
【问题描述】:

我是 kivy 的新手,我正在尝试在我的应用中实现购物车。我有一个名为 cart 的变量,它设置为 0。我想在按下按钮时添加到变量中,但是当我这样做时,我收到此错误 AssertionError: 7 is not callable。为什么我会准确地收到此错误,我该如何解决?

我尝试了一些方法,例如将 global 命令添加到 cart 并将变量放入 FirstScreen 类中,但它们都给出了相同的错误。我敢肯定,我错过了一些简单的事情,但任何帮助都会得到帮助!

这里是重现问题的示例代码。

.py 文件

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.core.window import Window
from kivy.properties import ObjectProperty
from kivy.uix.image import Image
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.uix.popup import Popup

cart = 0

class FirstScreen(Screen):
    def sizeSelection(self):
        sizepopup = FloatLayout()
        sizepop = Popup(title="Format", separator_color=[0.6, 0, 0, 1], content=sizepopup,title_font=("Gothic"), size_hint=(0.6, 0.6))
        sizepopup.add_widget(Label(text="Choose a format", font_name="Gothic", pos_hint={"x": 0, "y": 0.4}))
        sizepopup.add_widget(Button(text="Small", font_name="Gothic", size_hint=(1, 0.15), pos_hint={"x": 0, "y": 0.6}, on_release = cart + 7 ))
        sizepopup.add_widget(Button(text="Back", font_name="Gothic", size_hint=(0.8, 0.15), pos_hint={"x": 0.10, "y": 0}, on_release=sizepop.dismiss))
        sizepop.open()

class WindowManager(ScreenManager):
    pass

class exampleApp(App):
    def build(self):
        return WindowManager()

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

.kv 文件

<WindowManager>:
    FirstScreen:

<FirstScreen>:
    FloatLayout:
        Button:
            text: "Add to cart"
            size_hint: 0.5,0.1
            pos_hint: {"x": 0.25,"y":0.5}
            on_release:
                root.sizeSelection()

【问题讨论】:

    标签: variables button kivy cart shopping


    【解决方案1】:

    您可以通过将on_release 设置为递增cart 的方法来实现:

    sizepopup.add_widget(Button(text="Small", font_name="Gothic", size_hint=(1, 0.15), pos_hint={"x": 0, "y": 0.6}, on_release=self.increment_cart))
    

    然后,将该方法添加到FirstScreen 类中:

    def increment_cart(self, button):
        global cart
        cart += 7
        print('cart =', cart)
    

    【讨论】:

      猜你喜欢
      • 2021-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-28
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      相关资源
      最近更新 更多