使用 tkinter/python 我试图在按钮单击列表框 (tkinter) 时添加一个项目,但在新点击后只显示一个项目。
我创建列表框的代码是:
protect
更多点击按钮不添加新项目,可能是什么错误?
答案 0 :(得分:1)
每次按下按钮时,您都会不断创建新的列表框小部件。您必须创建 1 个列表框,并在按下按钮时插入数据,如下所示:
import tkinter as tk
def add_to_list(data):
listbox_widget.insert("end", data)
root = tk.Tk()
listbox_widget = tk.Listbox(root, width=40, height=4)
listbox_widget.pack()
command = lambda: add_to_list("hello new item")
button = tk.Button(root, text="Add", padx=8, pady=4, command=command)
button.pack()
root.mainloop()