这个问题在这里已有答案:
我试图让tkinter中的这个Listbox在点击按钮时从sqlite3数据库更新。我实际上使用root.after(1000,function)方法工作,但光标每次更新时都会保持重置。
目前我无法在按钮点击时填充列表框。
我很乐意帮忙。谢谢!
root=Tk()
ListBox1 = Listbox(root)
ListBox1.grid(row=0, column=0 , sticky='nsew')
def ListUpdate():
listlist = []
#populates list from sql database in a for loop
return listlist
def ListPopulate(listlist):
ListBox1.delete(0, END)
for i in range(0,len(listlist[i]):
ListBox1.insert(END, listlist[i])
ButtonUpdate = Button(root, text='Update', command=ListPopulate(listlist))
ButtonUpdate.grid(row=5, column=6, sticky='nsew')
你的command=
的Button
参数在创建按钮时调用ListPopulate(listlist)
并将其结果(这是None
,因为你不从该函数返回任何东西)作为命令。因此你告诉Button
对象它没有命令。
您自然会遇到问题,将列表传递到事件驱动系统中需要的所有位置。一种方法是使列表ListList
成为全局变量。使用其他变量在脚本顶部的所有函数之外定义它:
ListBox1 = Listbox(root)
ListBox1.grid(row=0, column=0 , sticky='nsew')
listlist = []
接下来,更改ListUpdate()
的第一行以使用切片分配清空现有列表对象,因此您无需在该函数中声明对象全局。
def ListUpdate():
listlist[:] = []
然后改变ListPopulate()
不采取任何参数,因为它将使用全局listlist
。
def ListPopulate():
最后,编写你的Button()
构造函数来传递ListPopulate
而不是调用它。
ButtonUpdate = Button(root, text='Update', command=ListPopulate)
全球通常是不好的做法。你应该做的是子类Listbox
并给它一个保存列表的属性。那么你的两个函数就是那个类的方法。 (事实上,你可能希望每次更改其内容时都更新屏幕上显示的列表...所以你应该有一个方法,而不是两个。)我将把它作为练习,当你学习面向对象的编程时。
你使用的命令错了。更换:
Button(..., command=ListPopulate(listlist))
有:
Button(..., command=lambda l=ListUpdate(): ListPopulate(l))