Python基于tkinter模块实现的改名小工具示例


Posted in Python onJuly 27, 2017

本文实例讲述了Python基于tkinter模块实现的改名小工具。分享给大家供大家参考,具体如下:

#!/usr/bin/env python
#coding=utf-8
# 
# 版权所有 2014 yao_yu
# 本代码以MIT许可协议发布
# 文件名批量加.xls后缀
# 2014-04-21 创建
# 
import os
import tkinter as tk
from tkinter  import ttk
version = '2014-04-21'
app_title = '文件名批量加后缀 Ver:' + version
listdir = os.listdir
isdir = os.path.isdir
isfile = os.path.isfile
path_join = os.path.join
#---------------------------- Object Visit  ----------------------------#
def visit_directory_files(root, visitor):
  for i in listdir(root):
    i = path_join(root, i)
    if isdir(i):
      if visit_directory_files(i, visitor):
        return True
    elif isfile(i):
      if visitor(i):
        return True
#----------------------------  Visitor  ----------------------------#
class ListVisitor(object):
  def __init__(self, *visitors, terminate = True):
    if (visitors 
         and isinstance(visitors, (list, tuple)) 
         and isinstance(visitors[0], (list, tuple))):
      visitors = visitors[0]
    self._visitors = list(visitors)
    self._terminate = terminate
  def __call__(self, *args, **kwdargs):
    for visitor in self._visitors:
      if visitor(*args, **kwdargs):
        return self._terminate
  def append(self, visitor):
    assert(visitor)
    self._visitors.append(visitor)
def get_screen_size(window):
  return window.winfo_screenwidth(),window.winfo_screenheight()
def get_window_size(window):
  return window.winfo_reqwidth(),window.winfo_reqheight()
def center_window(root, width, height):
  screenwidth = root.winfo_screenwidth()
  screenheight = root.winfo_screenheight()
  size = '%dx%d+%d+%d' % (width, height, (screenwidth - width)/2, (screenheight - height)/2)
  root.geometry(size)
class Application(object):
  def __init__(self, master):
    self.master = ttk.Frame(master)
    self.master.pack(side = tk.TOP, expand = tk.YES, fill = tk.BOTH)
    self.create_widgets()
  def create_widgets(self):
    master = self.master
    master.columnconfigure(1, weight=1)
    master.rowconfigure(2, weight=1)
    self.targetdir = tk.StringVar()
    self.targetdir.set('/Volumes/Data/Document/Test')
    padx = 5
    pady = 10
    ttk.Label(master, text="操作目录").grid(row = 0, column = 0, stick = tk.E, padx = padx, pady = pady)
    ttk.Entry(master, textvariable = self.targetdir).grid(row = 0, column = 1, stick = tk.EW, padx = padx)
    commands = ttk.Frame(master)
    commands.grid(row = 1, column = 0, columnspan = 2)
    ttk.Button(commands, text="开始", command = self.onStart).pack(side = tk.LEFT)
    ttk.Button(commands, text="退出", command = master.quit).pack(side = tk.LEFT)
    self.status = tk.StringVar()
    self.status.set('就绪')
    master.rowconfigure(3, minsize = 160)
    ttk.Label(master, textvariable = self.status, wraplength=600).grid(row = 3, column = 0, columnspan = 2, padx = padx, stick = tk.NSEW)
    self.progress = ttk.Progressbar(master, maximum=100, orient=tk.HORIZONTAL, mode='determinate')
    self.progress.grid(row = 4, column = 0, columnspan = 2, padx = padx, stick = tk.NSEW)
  def onStart(self):
    targetdir = self.targetdir.get().strip()
    basename = os.path.basename(targetdir)
    if os.path.isdir(targetdir):
      listvisitor = ListVisitor(ProgressVisitor(self.progress),
                    self.StatusVisitor(),
                    FileLogVisitor(basename),
                    #FileRenameVisitor(basename),
                    )
      visit_directory_files(targetdir, listvisitor)
    else:
      self.status.set('目标目录不存在')
  def StatusVisitor(self):
    print_status = self.status.set
    def __call__(file):
      __call__.n += 1
      print_status('%s,%s' % (__call__.n, file))
    __call__.n = 0
    return __call__
splitext = os.path.splitext
file_rename = os.rename
knownexts = dict.fromkeys(['.jpg', '.log', '.pdf', '.tif', '.xls', '.zip', '.rar'])
class FileRenameVisitor(object):
  def __init__(self, file):
    self.__fp = open('%s_%s_rename.txt' % (os.path.splitext(__file__)[0], file), 'w')
  def __call__(self, file):
    ext = splitext(file)[1].lower()
    if ext not in knownexts:
      file_rename(file, file + '.xls')
      self.__fp.write('%s\n' % file)
  def __del__(self):
    self.__fp.close()
class FileLogVisitor(object):
  def __init__(self, file):
    self.__fp = open('%s_%s_all.txt' % (os.path.splitext(__file__)[0], file), 'w')
  def __call__(self, file):
    self.__fp.write('%s\n' % file)
  def __del__(self):
    self.__fp.close()
class ProgressVisitor(object):
  COUNT = 202
  def __init__(self, progress, count=COUNT):
    self.progress = progress
    if count and isinstance(count, int) and count > 0:
      self.count = count
    else:
      self.count = self.COUNT
    self.n = 1
  def __call__(self, *args, **kwdargs):
    self.n += 1
    if self.n == self.count:
      self.progress.step()
      self.progress.update()
      self.n = 1
  def __del__(self):
    self.progress['value'] = 0
if __name__ == '__main__':
  root = tk.Tk()
  root.title(app_title)
  app = Application(root)
  center_window(root, 600, 240)
  tk.mainloop()

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
python实现bucket排序算法实例分析
May 04 Python
详解在Python的Django框架中创建模板库的方法
Jul 20 Python
详解 Python 读写XML文件的实例
Aug 02 Python
python3读取csv和xlsx文件的实例
Jun 22 Python
Pytorch 实现数据集自定义读取
Jan 18 Python
使用K.function()调试keras操作
Jun 17 Python
Python 创建TCP服务器的方法
Jul 28 Python
python从ftp获取文件并下载到本地
Dec 05 Python
python接口自动化框架实战
Dec 23 Python
python用700行代码实现http客户端
Jan 14 Python
python实现批量移动文件
Apr 05 Python
Python趣味挑战之用pygame实现简单的金币旋转效果
May 31 Python
python django 增删改查操作 数据库Mysql
Jul 27 #Python
Python中Selenium模拟JQuery滑动解锁实例
Jul 26 #Python
Python列表和元组的定义与使用操作示例
Jul 26 #Python
老生常谈Python之装饰器、迭代器和生成器
Jul 26 #Python
python基础之入门必看操作
Jul 26 #Python
Python简单定义与使用字典dict的方法示例
Jul 25 #Python
Python学习入门之区块链详解
Jul 25 #Python
You might like
一次编写,随处运行
2006/10/09 PHP
php strstr查找字符串中是否包含某些字符的查找函数
2010/06/03 PHP
php数组索引的Key加引号和不加引号的区别
2014/08/19 PHP
php中JSON的使用方法
2015/04/30 PHP
thinkphp配置文件路径的实现方法
2016/08/30 PHP
PHP封装的mysqli数据库操作类示例
2019/02/16 PHP
Laravel timestamps 设置为unix时间戳的方法
2019/10/11 PHP
用js闭包的方法实现多点标注冒泡示例
2014/05/29 Javascript
基于KO+BootStrap+MVC实现的分页控件代码分享
2016/11/07 Javascript
jQuery在header中设置请求信息的方法
2017/03/06 Javascript
Angular实现响应式表单
2017/08/04 Javascript
记一次webpack3升级webpack4的踩坑经历
2018/06/12 Javascript
layui 优化button按钮和弹出框的方法
2018/08/15 Javascript
Koa日志中间件封装开发详解
2019/03/09 Javascript
javascript创建元素和删除元素实例小结
2019/06/19 Javascript
JS 获取文件后缀,判断文件类型(比如是否为图片格式)
2020/05/09 Javascript
JavaScript实现缓动动画
2020/11/25 Javascript
Python不规范的日期字符串处理类
2014/06/10 Python
Python进阶_关于命名空间与作用域(详解)
2017/05/29 Python
Python实现返回数组中第i小元素的方法示例
2017/12/04 Python
python检索特定内容的文本文件实例
2018/06/05 Python
Python3模拟curl发送post请求操作示例
2019/05/03 Python
Python搭建Spark分布式集群环境
2019/07/05 Python
python实现读取excel文件中所有sheet操作示例
2019/08/09 Python
Tensorflow 1.0之后模型文件、权重数值的读取方式
2020/02/12 Python
Html5页面二次分享的实现
2018/07/30 HTML / CSS
AT&T Wireless:手机、无限数据计划和配件
2018/06/03 全球购物
计算机求职信
2013/12/01 职场文书
电子商务专业求职信
2014/03/08 职场文书
优质护理服务演讲稿
2014/05/07 职场文书
小学网上祭英烈活动总结
2014/07/05 职场文书
工商局局长个人对照检查材料思想汇报
2014/09/23 职场文书
2014最新实习证明模板
2014/10/02 职场文书
2014年电工工作总结
2014/11/20 职场文书
2015年信贷员工作总结
2015/04/28 职场文书
MySQL系列之八 MySQL服务器变量
2021/07/02 MySQL