如何实现动态tkinter-listboxes



因此,我得到了一些示例代码,说明如何在一个函数中本质上控制多个列表框,在示例代码中似乎可以工作,但在实现后,我很难看到我错过了什么。

示例代码:

import tkinter as tk
class MultiListbox(tk.Frame):
def __init__(self, parent):
super().__init__(parent)
for i in range(5):
lb = tk.Listbox(self, height=10, exportselection=False)
lb.pack(side="left", fill="y")
for j in range(10):
lb.insert("end", f"Listbox {i+1} value {j+1}")
lb.bind("<Double-1>", self.removeSeq)
def removeSeq(self, event):
lb = event.widget
curselection = lb.curselection()
index = curselection[0] if curselection else None
for listbox in self.winfo_children():
listbox.delete(index)

root = tk.Tk()
mlb = MultiListbox(root)
mlb.pack(side="top", fill="both", expand=True)
root.mainloop()

我试图实现逻辑的地方:

进口

import tkinter as tk,tkinter.ttk as ttk, pyautogui, numpy, easygui, cv2, os, time, _thread, re, math, subprocess
from tkinter import BOTH, END, LEFT
pyautogui.FAILSAFE = True

类别

class Acgm003App:
def __init__(self, master=None):

for i in range(5):
self.lb = tk.Listbox(self.modeSelect)
self.lb.configure(background='#2f2a2d', exportselection='false', font='{Arial} 12 {}', foreground='#feffff', height='23')
self.lb.configure(relief='flat', width='12')
self.lb.pack(side='left')
for j in range(10):
self.lb.insert("end", f"Listbox {i+1},{j+1}")
self.lb.bind("<Double-1>", self.getIndexLB)

功能

def getIndexLB(self, event):
print('hello')
self.lb = event.widget
curselection = self.lb.curselection()
index = curselection[0] if curselection else None
for listbox in self.lb.winfo_children():
print(index)
listbox.delete(index)
pass

我根本没有得到任何东西,我把print('hello')放在那里只是为了确保它装订正确,它打印得很好,但没有结果。

该代码旨在通过获取curselection的相应索引来删除其他列表框中的列表框项目,这有点像是对tk.treeview.的变通

如果你能帮忙,请告诉我!

我没有测试它,但我认为你用错了对象。

原始代码使用

lb = tk.Listbox(self, ...)

将列表框添加到self,然后在self中搜索children

for listbox in self.winfo_children():

您将列表框添加到self.modeSelect

tk.Listbox(self.modeSelect, ...)

所以你应该在self.modeSelect中搜索children

for listbox in self.modeSelect.winfo_children():

但是如果在self.modeSelect中添加其他小部件,这种方法可能会产生问题,因为它会尝试在其他小部件上也使用.delete(index)。然后你应该检查一下你是否得到了tk.Listbox

for child in self.modeSelect.winfo_children():
if isinstance(child, tk.Listbox):
child.delete(index)

编辑:

import tkinter as tk
class Acgm003App:
def __init__(self, master=None):

self.modeSelect = tk.Frame(master)
self.modeSelect.pack()

# other child in `self.modeSelect`
self.label = tk.Label(self.modeSelect, text="Hello World")
self.label.pack(side='top')

for i in range(5):
self.lb = tk.Listbox(self.modeSelect)
self.lb.pack(side='left')
for j in range(10):
self.lb.insert("end", f"Listbox {i+1},{j+1}")
self.lb.bind("<Double-1>", self.getIndexLB)
def getIndexLB(self, event):
self.lb = event.widget
curselection = self.lb.curselection()
index = curselection[0] if curselection else None
for child in self.modeSelect.winfo_children():
# check if child is `tk.Listbox` or other widget
if isinstance(child, tk.Listbox):
child.delete(index)
root = tk.Tk()
app = Acgm003App(root)
root.mainloop()

最新更新