【问题标题】:Where do I assign a variable in order for it to be used in a function (inside a class)?我在哪里分配一个变量才能在函数中(类内部)使用它?
【发布时间】:2019-04-23 07:36:27
【问题描述】:

我正在使用 tkinter 创建一个类,它允许您输入多个产品的信息,除了更改输入字段以设置其他产品的值之外,我已经完成了所有其他操作。

我将产品转换过程放入一个名为 saveVars 的函数中,它将输入的信息保存到特定的产品变量中,然后清除输入字段,并切换要在第二个产品变量上执行的 saveVars。

    i = 1

    def saveVars(i):
        if i == 1:
            product1.productName = self.prodName.get()
            product1.productID = self.prodID.get()
            product1.productSize = self.prodSize.get()
            product1.productPrice = self.prodPrice.get()
            product1.productQuant = self.quantity.get()
        elif i == 2:
            product2.productName = self.prodName.get()
            product2.productName = self.prodID.get()
            product2.productSize = self.prodSize.get()
            product2.productPrice = self.prodPrice.get()
            product2.productQuant = self.quantity.get()
        elif i == 3:
            product3.productName = self.prodName.get()
            product3.productName = self.prodID.get()
            product3.productSize = self.prodSize.get()
            product3.productPrice = self.prodPrice.get()
            product3.productQuant = self.quantity.get()
        newProduct()
        i += 1
        return i

我希望它能够根据 +1 函数将条目保存到的变量切换到下一个相应的产品,我让它将 i 函数作为新 i 返回,然后应该保存过程中下一个变量的条目,但它一直告诉我我'缺少 1 个必需的位置参数:'i'

【问题讨论】:

  • 你怎么打电话给saveVars
  • 我在一个更大的类中调用它,该类创建 gui、标签、条目以及基本上所有其他内容。 @Sayse
  • 特别是我按下了一个按钮来激活这个功能@Sayse
  • 你能显示对saveVars的实际函数调用
  • addItemButton = Button(window, text = "Add to Cart", fg='black',bg='yellow',width = 10, height = 2, command = saveVars) addItemButton.place( x=800,y=375) @AshishGhodake

标签: python function tkinter


【解决方案1】:

您正在尝试调用不带参数的函数,因为command 属性不带参数只是函数的名称。

要传递参数,您可以使用 partial 形式 functools

进口声明:

from functools import partial

您对函数的调用如下所示:

addItemButton = Button(window, text = "Add to Cart", fg='black',bg='yellow',width = 10, height = 2, command = partial(saveVars,i)) addItemButton.place(x=800,y=375)

您可以在您的类中使用全局变量将初始值设置为i,而不是在类外声明它。您可以将其保存在您希望的任何位置,并在调用该函数时传递它。

【讨论】:

    【解决方案2】:

    在某些情况下,您似乎正在调用没有参数的 saveVars。为了防止这种情况,您可以设置默认值 i,例如。

    def saveVars(i=0)
    

    【讨论】:

    • 所以我尝试了这个,但不幸的是它只保存第一个产品,因为它一直默认为 1 或任何预先确定的数字,这就是为什么我认为建立 i 是个好主意函数外的变量,然后在函数内+1并返回它,所以它每次都会增加一。 @IshitaSingh
    • 是的,继续你的递增逻辑,但如果没有传递“i”,则将其添加为默认值:``` def saveVars(i=1) ``` 运行你以前的代码只是这个变化。错误应该会消失。
    猜你喜欢
    • 1970-01-01
    • 2011-03-07
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 2019-05-28
    • 1970-01-01
    • 2016-10-20
    • 1970-01-01
    相关资源
    最近更新 更多