首页 > 解决方案 > “MultiColumnListbox”对象没有属性“curselection”

问题描述

我的 MultiColumnListbox 出现错误。我正在尝试了解如何解决此问题。我正在尝试查看在我的多列列表框中选择的内容。多列列表框是使用 tkinter 构建的,并且有一个提交按钮,该按钮应该运行一个函数,告诉我在多列列表框中选择了哪些行。我收到此错误“MultiColumnListbox”对象没有属性“curselection”并且似乎无法修复它。

这是我的代码

import os
import time
import glob
import datetime
from array import *
try:
    import Tkinter as tk
    import tkFont
    import ttk
except ImportError:  # Python 3
    import tkinter as tk
    import tkinter.font as tkFont
    import tkinter.ttk as ttk

class MultiColumnListbox(object):
    """use a ttk.TreeView as a multicolumn ListBox"""

    def submitFunction():
        selection = listbox.curselection()
        for k in range(0,len(selection)):
            selected = listbox.curselection()[k]

    def __init__(self):
        self.tree = None
        self._setup_widgets()
        self._build_tree()

    def _setup_widgets(self):
        s = """\click on header to sort by that column
to change width of column drag boundary
        """
        msg = ttk.Label(wraplength="4i", justify="left", anchor="n",
            padding=(10, 2, 10, 6), text=s)
        msg.pack(fill='x')
        container = ttk.Frame()
        container.pack(fill='both', expand=True)
        # create a treeview with dual scrollbars
        self.tree = ttk.Treeview(columns=car_header, show="headings")
        vsb = ttk.Scrollbar(orient="vertical",
            command=self.tree.yview)
        hsb = ttk.Scrollbar(orient="horizontal",
            command=self.tree.xview)
        self.tree.configure(yscrollcommand=vsb.set,
            xscrollcommand=hsb.set)
        self.tree.grid(column=0, row=0, sticky='nsew', in_=container)
        vsb.grid(column=1, row=0, sticky='ns', in_=container)
        hsb.grid(column=0, row=1, sticky='ew', in_=container)
        container.grid_columnconfigure(0, weight=1)
        container.grid_rowconfigure(0, weight=1)

    def _build_tree(self):
        for col in car_header:
            self.tree.heading(col, text=col.title(),
                command=lambda c=col: sortby(self.tree, c, 0))
            # adjust the column's width to the header string
            self.tree.column(col,
                width=tkFont.Font().measure(col.title()))

        for item in car_list:
            self.tree.insert('', 'end', values=item)
            # adjust column's width if necessary to fit each value
            for ix, val in enumerate(item):
                col_w = tkFont.Font().measure(val)
                if self.tree.column(car_header[ix],width=None)<col_w:
                    self.tree.column(car_header[ix], width=col_w)

def sortby(tree, col, descending):
    """sort tree contents when a column header is clicked on"""
    # grab values to sort
    data = [(tree.set(child, col), child) \
        for child in tree.get_children('')]
    # if the data to be sorted is numeric change to float
    #data =  change_numeric(data)
    # now sort the data in place
    data.sort(reverse=descending)
    for ix, item in enumerate(data):
        tree.move(item[1], '', ix)
    # switch the heading so it will sort in the opposite direction
    tree.heading(col, command=lambda col=col: sortby(tree, col, \
        int(not descending)))

FilesToDeleteName = [];
FilesToDeletePath = [];
FilesToDeleteDate = [];
car_list = [];
car_list.append([])
car_list.append([])

#str1 = input("Enter number of days old: ")
#days = int(str1)
days = 90
count = 0
time_in_secs = time.time() - (days * 24 * 60 * 60)

extf = ['Windows','Program Files', 'Program Files (x86)']

for (root, dirs, files) in os.walk('C:/Users', topdown=True):
    dirs[:] = [d for d in dirs if d not in extf]
    for filename in files:
        Fullname = os.path.join(root,filename)
        stat = os.stat(Fullname)
        modified = datetime.datetime.fromtimestamp(stat.st_mtime)
        if Fullname.endswith('.pcapng') or Fullname.endswith('.evtx') or Fullname.endswith('.png') or Fullname.endswith('.sql') or Fullname.endswith('.etl') or Fullname.endswith('.zip'):
            if stat.st_mtime <= time_in_secs:
                FilesToDeleteName.append(filename);
                FilesToDeletePath.append(Fullname);
                FilesToDeleteDate.append(str(modified));


FilesToDelete = [];

for p in range(0,len(FilesToDeletePath)):
    STR2 = FilesToDeletePath[p],FilesToDeleteDate[p]
    FilesToDelete.append(STR2)

car_list = FilesToDelete

car_header = ["Path ", "Date Modified"]

if __name__ == '__main__':
    window = tk.Tk()
    window.title("Multicolumn Treeview/Listbox")
    listbox = MultiColumnListbox()

    def submitFunction():
        print(listbox.curselection(self))
        window.destroy()

    def closeFunction():
        window.destroy()

    submit = tk.Button(window, text='Submit', command=submitFunction)
    submit.pack(side=tk.RIGHT, padx = 20)

    close = tk.Button(window, text='Close', command=closeFunction)
    close.pack(side=tk.RIGHT)

    window.mainloop()

这是我的问题的主要部分

        def submitFunction():
        print(listbox.curselection(self))
        window.destroy()

我最终将尝试获取索引号以删除给定的文件路径

标签: pythonpython-3.xtkinter

解决方案


推荐阅读