如果已选择项目并按下按钮,如何从列表框中删除项目

时间:2017-07-06 15:17:22

标签: python python-3.x user-interface tkinter listbox

我正在创建一个在冰箱上使用的应用程序,以便用户可以通过GUI屏幕上的列表框查看冰箱中的项目,然后当他们删除项目时,他们可以按下列表上的该项目框并按下删除该项目将从列表框中删除的位置。

但是我在如何使用按钮从列表中删除项目方面遇到了问题(如果这样做有意义的话)。

这是我的代码;

  def Pud():
        window = Tk()
        window.title('Listbox Example')

        def dialog():
***#########Somehere around here i belive should be where the item is removed from the list box########***

            box.showinfo('Selection','Item taken from the fridge: \n'+ \
            listbox.get(listbox.curselection()))

        frame = Frame(window)

        listbox = Listbox(window)
        listbox.pack()
        Items_In_Fridge = ['Milk', 'Butter']
        for widget in Items_In_Fridge:
            listbox.insert(0, widget)

        btn = Button(window,text = 'Remove This Item',command=dialog)

        btn.pack(side = RIGHT,padx = 5)
        listbox.pack(side = LEFT)

        window.mainloop()

我知道代码应该在哪里但是我不确定代码是什么或如何根据我的需要对其进行格式化,我已经尝试了多种方法来尝试完成此操作但是没有成功。

我将非常感谢任何帮助我正在使用python 3

1 个答案:

答案 0 :(得分:1)

捕获对话框的响应。如果用户说“是”,请删除该项目。

response = messagebox.askquestion ('Delete Item','Delete the item taken from the fridge?\n'+ \
    listbox.get(listbox.curselection()))
if response == 'yes':
    listbox.delete(listbox.curselection())