正在努力找到一种方法使Tkinter Listbox有一个删除数组中相应项的按钮

2024-10-01 19:24:47 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,这是一个很难解释的问题,但我要试一下

我创建了一个数组,其中包含一些'items',并将该数组中的那些项(使用for循环,这样无论数组中有多少项,它都可以工作)放入一个列表框中,您可以在其中选择一个要删除的项。但是,由于我使用了for循环,列表框中的项没有可以关联的编号,因此无法删除所需的项

下面是我目前使用的代码:

from tkinter import *
import tkinter.messagebox as box
global num
num = 1

inventorylist = ["Item1","Item2","Item3","Item4"]

def remove():
   global i
   del inventorylist[i]
   situation_I()


def situation_IR():
   global num
   if num == 1:
       windowi.destroy()
       num = 2

   global windowir
   windowir = Tk()
   windowir.title( "IR" )

   listframe = Frame( windowir )
   listbox = Listbox( listframe )

   global i

   for i in range(len(inventorylist)):
       e = i+1
       listbox.insert(e, inventorylist[i])


   btn_ir_1 = Button( listframe, text = "Remove", command = remove )
   btn_ir_1.pack(side = RIGHT, padx = 5)

   listbox.pack(side = LEFT)

   listframe.pack(padx = 30, pady = 30)


   windowir.mainloop


def situation_I():
   global num

   if num == 2:
       windowir.destroy()
       num = 1

   global windowi
   windowi = Tk()
   windowi.title( "I" )

   Btn_i = Button( windowi, text = "Remove item", command = situation_IR )
   Btn_i.grid( row = 61, column = 76, columnspan = 50 )

   Label_i = Label( windowi, relief = "groove", width = 50 )
   Label_i.grid( row = 1, column = 76, rowspan = 50, columnspan = 100, padx = ( 10, 10 ) )

   all_lines = []

   for i in range(0, len(inventorylist), 3):
       line = ", ".join(inventorylist[i:i+3])
       all_lines.append(line)

   words = ",\n".join(all_lines)

   Label_i.configure( text = words )


   windowi.mainloop()



situation_I()

此时,它只是删除数组中的最后一个项,不管发生什么


Tags: textforirdef数组globalnumlabel
1条回答
网友
1楼 · 发布于 2024-10-01 19:24:47

这应该是可行的,使用curselection()来查找所选项目的索引,下面给出了代码,我希望它能解决您的问题

import tkinter as tk

class Root(tk.Tk):
    list = ['Item1', 'Item2', 'Item3', 'Item4']
    def __init__(self):
        super().__init__()
        box = tk.Listbox(self)
        btn = tk.Button(self, text = 'Remove', command = lambda: self.rmv(box))
        for item in Root.list: box.insert(tk.END, item)
        box.pack(side = 'top')
        btn.pack(side = 'bottom')

    def rmv(self, *args):
        box, = args
        try:
            ind = box.curselection()[0]
            del Root.list[ind] #To delete values in the list too. 
            box.delete(ind)
        except:
            pass

if __name__ == '__main__':
    Root().mainloop()

相关问题 更多 >

    热门问题