<small id='s76OHh0fmi'></small> <noframes id='dk3V'>

  • <tfoot id='Xz71'></tfoot>

      <legend id='KmZYDiT9l'><style id='gw7Cpnc'><dir id='CJV29Bro70'><q id='rkGD2HeQ'></q></dir></style></legend>
      <i id='5360'><tr id='VwxGILcy'><dt id='ZlqAiV'><q id='q4yLdpxYM'><span id='Pxye3o6qtf'><b id='9yfoKIFWl'><form id='yKvPpQgd'><ins id='KP1mBSp'></ins><ul id='l6Kr'></ul><sub id='H4KTnm'></sub></form><legend id='5uBP8gzJv'></legend><bdo id='FcpLz3'><pre id='RPUtW'><center id='NEwOda'></center></pre></bdo></b><th id='is857'></th></span></q></dt></tr></i><div id='mBTzYp'><tfoot id='fmzl'></tfoot><dl id='s4vcdL2k'><fieldset id='elLhd'></fieldset></dl></div>

          <bdo id='zO72D'></bdo><ul id='IAvnyuG'></ul>

          1. <li id='Fpkl9W'></li>
            登陆

            Python GUI编程入门(37)-通用的ListView类

            admin 2020-02-14 154人围观 ,发现0个评论

            Tkinter主题控件的Treeview除了体统树状视图之外,还能够供给列表视图。可是因为控件本身的复杂性,假如想正确的运用这个控件,或多或少都需求一些时刻来调查和学习。本文供给一个通用的ListView类以简化这个进程。

            这个类除了供给一般的列表功用之外,还供给一个简略的就地修正功用:当用户双击文件名时,能够触发一个文本输入框直接修正文件名。

            class ListView(Treeview):
            def __init__(self, master, **kwargs):
            columns = kwargs.get('columns')
            kwargs.pop('columns')
            Treeview.__init__(self, master)
            if columns:
            cols = []
            for c in range(1, columns):
            cols.append('#{}'.format(c))
            self['columns'] = cols
            self.editable = {}
            self.bind('<>', self.item_selected)
            self.bind('', self.item_double_clicked) # 双击左键进入修正
            # 设定答应修正的列
            def enable_edit(self, col, editable):
            self.editable[col] = editable
            # 双击处理
            def item_double_clicked(self, event):
            column = self.identify_column(event.x) # 列
            row = self.identify_row(event.y) # 行
            editable = self.ePython GUI编程入门(37)-通用的ListView类ditable.get(column)
            if editable:
            ItemEdit(self, row, column)
            # 修正成果承认处理
            def entry_confirmed(self, row, col, text):
            self.set_text(row, col, text)
            # 行选中处理
            def item_selected(self, event):
            try:
            self.master.item_selected(event)
            except:
            pass
            # 指定队伍获取内容
            def get_text(self, row, col):
            if col == '#0':
            return self.item(row, 'text')
            else:
            return self.set(row, col)
            # 指定队伍修正内容
            def set_text(self, row, col, text):
            if col == '#0':
            self.item(row, text=text)
            else:
            self.set(row, col, text)

            这个类承继自Tkinter的Treeview类,除了供给了get_text和set_text两个函数之外,主要是完成的就地修正功用。这是ListView需求合作ItemEdit类运用:

            class ItemEdit(Entry):
            def __init__(self, view, row, col):
            Entry.__init__(self, view)
            bbox = view.bbox(row, col)
            cur_width = self['width']
            req_width = self.winfo_reqwidth()
            width = int(cur_width * bbox[2] / req_width)
            self.configure(width=width)
            cur_width = self['width']
            req_width = self.winfo_reqwidth()
            width = int(cur_width * bbox[2] / req_width)
            self.configure(width=width)
            req_width = self.winfo_reqwidth()
            self.insert(INSERT, view.get_text(row, col))
            self.view = view
            self.row = row
            self.col = col
            self.place(x=bbox[0]+(bbox[2]-req_width)/2, y=bbox[1]-1)
            self.bind('', self.confirm)
            self.bind('', self.confirm)
            self.focus_set()
            self.update()
            self.bind('', self.confirm)
            def confirm(self, event):
            self.view.entry_confirmed(self.row, self.col, self.get())
            self.destroy()
            def config(self, event):
            print(event)

            ItemEdit类承继自Entry类,当用户按下修正控件内容并按下回车键是,将改变内容告诉给ListView并毁掉本身。除了按下回车键之外,Entry失掉焦点或许替换主题时也会触发相同的处理。

            有了这个ListView类之后,FileBroswer经过一个FileList类来完成目录内容显现和文件操作功用。

            class FileList(ListView):
            def __init__(self, master, **kwargs):
            ListView.__init__(self, master, columns=5, size_grip=True)
            self.column("#0", width=150, minwidth=150, stretch=YES)
            self.column("#1", width=150, minwidth=150, stretch=YES)
            self.column("#2", width=100,Python GUI编程入门(37)-通用的ListView类 minwidth=100, stretch=YES)
            self.column("#3", width=100, minwidth=100, stretch=NO)
            self.column("#4", width=100, minwidth=50, stretch=YES)
            self.heading("#0", text="Name", anchor=W)
            self.heading("#1", text="Date modified", anchor=W)
            self.heading("#2", text="Type", anchor=W)
            self.heading("#3", text="Size", anchor=W)
            self.enablePython GUI编程入门(37)-通用的ListView类_edit('#0', True)
            self.tree_view = kwargs.get('tree_view')
            # 绑定鼠标右键
            self.bind('', self.popup_menu)
            def entry_confirmed(self, row, col, text):
            prev = self.get_text(row, col)
            if text != prev:
            path = self.tree_view.current_path()
            if path:
            try:
            src = os.path.join(path, prev)
            des = os.path.join(path, text)
            os.rename(src, des)
            self.set_text(row, col, text)
            except Exception as e:
            showerror('Error', str(e))
            def selected_files(self):
            try:
            dir_node = self.tree_view.focus()
            if dir_node:
            path = self.tree_view.node_path(dir_node)
            return path, map(lambda x: self.item(x, 'text'), self.selection())
            except Exception as e:
            showerror('Error', str(e))
            return None
            def open_current(self):
            path, selections = self.selected_files()
            if path:
            for fn in selections:
            os.startfile(os.path.join(path, fn))
            def rename_current(self):
            path, selections = self.selected_files()
            if path:
            for Python GUI编程入门(37)-通用的ListView类fn in selections:
            dlg = RenameDialog(self, path, fn)
            self.sePython GUI编程入门(37)-通用的ListView类lect_node(None)
            def delete_current(self):
            path, selections = self.selected_files()
            if path and askokcancel('askokcancel', 'Delete the file has been selected?'):
            try:
            for fn in selections:
            os.remove(os.path.join(path, fn))
            except Exception as e:
            showerror('Delete file Error', str(e))
            self.select_node(None)
            def popup_menu(self, event):
            iid = self.identify_row(event.y)
            if iid:
            if iid not in self.selection():
            self.selection_set(iid)
            self.focus(iid)
            path, selections = self.selected_files()
            if path:
            menu = Menu(self, tearoff=False)
            menu.add_command(label='Open', commanPython GUI编程入门(37)-通用的ListView类d=self.open_current)
            if len(list(selections)) == 1:
            menu.add_command(label='Rename', command=self.rename_current)
            menu.add_command(label='Delete', command=self.delete_current)
            menu.post(event.x_root, event.y_root)
            def select_node(self, event):
            children = self.get_children('')
            for c in children:
            self.delete(c)
            focus = self.tree_view.focus()
            path = self.tree_view.node_path(focus)
            if os.path.isdir(path):
            try:
            dir_items = os.scandir(path)
            iid = 0
            for item in dir_items:
            if item.is_file() and ('.$'.find(item.name[0]) < 0):
            stat_info = os.stat(item.path)
            m_time = time.strftime("%Y/%m/%d %H:%M", time.localtime(stat_info.st_mtime))
            type = ' File'
            dot_pos = item.name.rfind('.')
            if dot_pos > 0:
            type = item.name[dot_pos + 1:].upper() + type
            self.insert('', 'end风流', str(iid), text=item.name, values=(m_time, type, stat_info.st_size))
            iid += 1
            except Exception as e:
            print(e)

            代码的内容和前面文章中阐明的没有差异,仅仅将相关功用会集到一个类中,这样代码的内聚性更好。接下来运用这个类的代码就简略了:

            detail_area, list_view = scrollable(paned_window, FileList, tree_view=tree_view)
            paned_window.add(detail_area)
            tree_view.bind('<>', list_view.select_node)

            完好代码能够从以下地址下载:

            https://github.com/xueweiguo/TkinterPrimer/blob/master/FileBrowser


            觉得本文有协助?请共享给更多人。

            更多更新文章,请重视【面向对象考虑】。

            面向对象规划,面向对象编程,面向对象考虑!

            请关注微信公众号
            微信二维码
            不容错过
            Powered By Z-BlogPHP