Python 3.4.2,使用listbox作为库存

时间:2016-05-24 11:48:23

标签: tkinter listbox python-3.4

我正在尝试创建一个系统,使用列表框从列表中选择项目,一旦按下某个项目,系统会询问用户是否要使用此项目。如果他们按是,则该项目将从列表中删除。

我的问题是我无法弄清楚如何正确编程,这样一旦从列表中选择一个项目,就会运行使用该项目的命令。这是代码,但前25行可以忽略,因为它们只是用于调出GUI,询问用户是否想要使用该项:

from tkinter import *
def YNquestion(questionString): #putting the code necessary for the GUI into a function allows it to be called every time the quesiton is asked
    global answer #allows the vaiable to be used anywhere in the program 
    def yes_command(): #called by the GUI to change the variable when the button is clicked
        answer.set('yes') #.set allows this to exit the GUI as it is a gloabal variable
        window.destroy() #closes the GUI window so the program does no become stuck
    def no_command(): #similar to the procedure above but sets the variable to 'no'
        answer.set('no')
        window.destroy()

    window = Tk() #creates GUI window 

    yes_no_label = Label(window, text=questionString) #sets the label text within this GUI specified as 'window', set to the string specified when called so this can be used in multiple ways such as in tic tac toe or setting gender of character
    yes_no_label.grid(row=0, column=1) #sets a place for the label to be displayed on the GUI

    answer=StringVar() #needed when running Tkinter with multiple Tk instances to allow variable to be used outside of program (value cannot be assigned within tkinter). 

    YESbutton = Button(window, text="Yes", fg='green', command = lambda :yes_command()) #sets the button with test and colour deatils, as well as what happens when pressed. 
    YESbutton.grid(row=1, column=0) #sets button location
    NObutton = Button(window, text = 'No', fg = 'red', command= lambda :no_command()) #same as for button above
    NObutton.grid(row=1, column=2)

    window.mainloop() #required to create the GUI which is essentially an infinite loop waiting for changes (button press)


#this is the seciton of code that handles how the inventory system works
inventory = ["Water", "Rabbit Meat"]
def water():
    YNquestion('Water will restore 5 energy. Use it?') #calls GUI which sets variable and asks for label text as arguement
    choice = answer.get()
    if choice == 'yes':
        print('You have restored 5 energy!')
    else:
        YNquestion.quit 

def inventoryCommand():    
    window = Tk()

    listboxInventory = Listbox(window)
    listboxInventory.pack()

    listboxInventory.insert(END, "Choose an item to use this turn!")

    for item in inventory:
        listboxInventory.insert(END, item)

    turn = True
    while turn == True:
        listboxInventory.curselection()


    mainloop()
inventoryCommand()

在我到目前为止尝试创建的内容中,我只尝试编写按下“水”时发生的事情。 谢谢你的帮助!

以下评论非常有帮助!我修改了代码以使其更整洁,并且使用消息框的方法在某种程度上起作用:

来自tkinter import *     来自tkinter import messagebox     库存= [“水”,“兔肉”]

#this is the section of code that handles how the inventory system works        
def delete_item(listboxInventory, event = None):
    answer = messagebox.askquestion("Delete", "Are You Sure?", icon='warning')
    if answer == 'yes': 
        if listboxInventory.curselection() == "Water":
            listboxInventory.delete(listboxInventory.curselection())
            inventory.remove("Water")
            print ("5 Energy has been restored!")
        elif listboxInventory.curselection() == "Rabbit Meat":
            listboxInventory.delete(listboxInventory.curselection())
            inventory.remove("Rabbit Meat")
            print ("3 Health has been restored!")

def inventoryCommand():    
    window = Tk()

    listboxInventory = Listbox(window)
    listboxInventory.pack()
    listboxInventory.bind('<<ListboxSelect>>', lambda _: delete_item(listboxInventory))
    listboxInventory.insert(END, "New item")  

    for item in inventory:
        listboxInventory.insert(END, item)

    mainloop()
inventoryCommand()

但是,我现在遇到的问题是我无法弄清楚如何从列表和列表框中删除该项目。显然,我上面的代码不允许使用listboxInventory.curselection作为参数进行分支。这是否意味着最好废弃基本库存清单并只使用一个特定的列表框?我最初的想法是,我可以有一个列表,并在使用项目时附加或删除它但我不再确定是否可能。

我还希望这样做,以便消息特定于项目,以便用户确切知道他们在做什么。然后我会在使用该项目后输出。它如上所示,但由于分支语句不起作用,我无法测试它是否会以这种方式工作。

很抱歉让这么复杂,我真的很感激任何帮助!

1 个答案:

答案 0 :(得分:0)

首先你需要删除它。它会永远循环:

turn = True
while turn == True:
    listboxInventory.curselection()

然后,导入将用于询问确认消息的消息框:from tkinter import messagebox。 现在,您可以创建一个每次用户选择项目时都会调用的函数:

def delete_item(listboxInventory, event = None):
    answer = messagebox.askquestion("Delete", "Are You Sure?", icon='warning')
    if answer == 'yes': 
        listboxInventory.delete(listboxInventory.curselection())

最后,像这样绑定它:

listboxInventory.bind('<<ListboxSelect>>', lambda _: delete_item(listboxInventory))