尝试将值从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 :(得分:0)
我会更正代码中的拼写错误,以便在解释中保持一致
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已通过。
此异常是因为title
函数中的saveData
参数,因此如果您希望将某些内容作为参数传递,则需要返回一个内部使用该参数的回调,但它不接受任何参数:
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
,您必须检索不带参数的函数,并将该变量用作闭包。如果代码的任何部分不适合您,请告诉我们!