python sqlite3通过按下按钮将spinbox中的值保存到数据库中

2024-10-02 16:23:53 发布

您现在位置:Python中文网/ 问答频道 /正文

正在尝试将spinbox中的值保存到我的数据库中。这是我代码的一部分。你知道吗

numericupdownLL = tk.Spinbox(self, from_=0, to=300)
numericupdownLL.pack()

def saveDate(title):
        vLL = int(numericupdownLL.get()) ## convert to int because output of spinbox= str and database=int
        c.execute("UPDATE settings SET ll=? WHERE name=?",(vLL, title))
        conn.commit()

buttonSave = tk.Button(self, text='save', command=saveData(something)
buttonSave.pack()

现在我没有得到任何错误,但是代码总是将一个0写入我的db,而不是spinbox的值。你知道吗

你知道吗?你知道吗


Tags: to代码fromself数据库titledefpack
1条回答
网友
1楼 · 发布于 2024-10-02 16:23:53

为了使解释一致,我将更正代码中的拼写错误

numericupdownLL = tk.Spinbox(self, from_=0, to=300)
numericupdownLL.pack()

# Changed saveDate to saveData that it's actually called in the button
def saveData(title):
    # Corrected indentation
    vLL = int(numericupdownLL.get())
    c.execute("UPDATE settings SET ll=? WHERE name=?",(vLL, title))
    conn.commit()

# Added a missing parentheses
buttonSave = tk.Button(self, text='save', command=saveData(something))
buttonSave.pack()

两个注意事项:

  • 我将引用此代码而不是您的代码,主要是因为按钮中调用的函数的名称与声明的函数的名称不匹配。你知道吗
  • 至于我不知道你的代码看起来如何,我将假设其余的代码都能正常工作。你知道吗

让我们开始:

首先要注意的是,您只调用函数一次,而不是每次单击按钮。这是因为不是传递函数,而是传递一个None,这是函数调用的返回。所以要解决这个问题,你应该去掉括号,把函数作为回调传递

# WARNING! This code does not work! Keep reading!
buttonSave = tk.Button(self, text='save', command=saveData)

更正后,每次单击该按钮时,都会出现一个异常,告诉您函数需要1个参数,并传递0。 此异常是由于saveData函数中的title参数引起的,因此如果希望将某个参数作为参数传递,则需要返回一个回调,该回调在内部使用该参数,但不接受任何参数:

def get_save_data_fn(title):
    def saveData():
        vLL = int(numericupdownLL.get())
        c.execute("UPDATE settings SET ll=? WHERE name=?",(vLL, title))
        conn.commit()
    return saveData  # Returns a function with 0 parameters that uses the given title

# Now you can retrieve the function that takes no arguments and has 'something' used 
# in the sql statement
buttonSave = tk.Button(self, text='save', command=get_save_data_fn(something))

所以最后的代码应该是这样的:

numericupdownLL = tk.Spinbox(self, from_=0, to=300)
numericupdownLL.pack()

def get_save_data_fn(title):
    def saveData():
        vLL = int(numericupdownLL.get())
        c.execute("UPDATE settings SET ll=? WHERE name=?",(vLL, title))
        conn.commit()
    return saveData  # Returns a function with 0 parameters that uses the given title

# Now you can retrieve the function that takes no arguments and has 'something' used 
# in the sql statement
buttonSave = tk.Button(self, text='save', command=get_save_data_fn(something))
buttonSave.pack()

总结:

  • 函数似乎没有被调用的原因是,在创建按钮时它只被调用一次,并且不再被调用,因为您没有将该函数传递给命令参数,但是没有传递给命令参数。你知道吗
  • 为了在回调中使用something,您必须检索一个没有参数的函数,并将该变量用作闭包。你知道吗

如果代码的任何部分不适合你,请告诉我!你知道吗

相关问题 更多 >