我目前有一个功能,当点击一个按钮时会创建2个输入框。需要将这些输入框的值输入数据库。这样做的问题是,每次单击按钮时,输入框的名称都与之前的名称相同。这意味着如果单击按钮两次,那么当它被提交到数据库时,只输入最后一组框中的值。这是代码:
def new(self):
global ExerciseCount
ExerciseCount = ExerciseCount + 1
print (ExerciseCount)
for num in range(ExerciseCount):
self.Exercises = Entry(self.FrameExercise, bg = "PaleTurquoise1", font =("Arial","16"), width = 20)
self.Exercises.grid(row=2+ExerciseCount, column=1)
global WeightCount
WeightCount = WeightCount + 1
print (WeightCount)
for num in range(WeightCount):
self.Weights = Entry(self.FrameExercise, bg = "PaleTurquoise1", font =("Arial","16"), width = 4)
self.Weights.grid(row=2+WeightCount, column=2)
def Update(self):
global MemberID
connection = sqlite3.connect(r"F:\TESTING\Program\Accounts.db")
cursor = connection.cursor()
Exercise = self.Exercises.get()
Weight = self.Weights.get()
ID = self.ent_MemberID.get()
cursor.execute("INSERT INTO Exercises (Exercise, Weight, ID) VALUES (?,?,?)",
(Exercise, Weight, ID,))
connection.commit()
单击该按钮时,仅将最后一组输入框提交到数据库。这可能是由我使用.get()
从条目中检索值,但我不知道任何替代方法,因为我仍然只是一名学生。
我还尝试通过为它们分配一个数字来迭代输入框但是它出现时出现错误,表示无法分配函数。
如果有任何方法可以在每个输入框中获取值,我将不胜感激。
答案 0 :(得分:1)
尝试在创建文本框时将其存储在数组中。然后使用该数组访问它们。这是一个例子:
import Tkinter as tk
class MyApplication(tk.Frame):
arr = []
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.pack()
self.createWidgets()
def addTextBox(self,event):
newtext = tk.Entry(self)
self.arr.append(newtext)
newtext.pack()
def getValues(self,event):
for i in range(len(self.arr)):
print self.arr[i].get()
def createWidgets(self):
self.btnAdd = tk.Button(self)
self.btnAdd["text"] = "Add"
self.btnAdd.bind("<Button-1>", self.addTextBox)
self.btnAdd.pack()
self.btnGet = tk.Button(self)
self.btnGet["text"] = "Get"
self.btnGet.bind("<Button-1>", self.getValues)
self.btnGet.pack()
# main
root = tk.Tk()
root.minsize(width=325, height=325)
root.maxsize(width=325, height=325)
app = MyApplication(master=root)
app.mainloop()