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 相关文章推荐
在SAE上部署Python的Django框架的一些问题汇总
May 30 Python
python 文件操作api(文件操作函数)
Aug 28 Python
深入浅析python with语句简介
Apr 11 Python
Selenium定位元素操作示例
Aug 10 Python
python paramiko利用sftp上传目录到远程的实例
Jan 03 Python
Python 微信爬虫完整实例【单线程与多线程】
Jul 06 Python
应用OpenCV和Python进行SIFT算法的实现详解
Aug 21 Python
Python 解决OPEN读文件报错 ,路径以及r的问题
Dec 19 Python
python numpy矩阵信息说明,shape,size,dtype
May 22 Python
python logging 重复写日志问题解决办法详解
Aug 04 Python
怎么解决pycharm license Acti的方法
Oct 28 Python
python更新数据库中某个字段的数据(方法详解)
Nov 18 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
php自动获取目录下的模板的代码
2010/08/08 PHP
PHP设计模式之结构模式的深入解析
2013/06/13 PHP
php获取URL中带#号等特殊符号参数的解决方法
2014/09/02 PHP
Yii中CGridView禁止列排序的设置方法
2016/07/12 PHP
滚动经典最新话题[prototype框架]下编写
2006/10/03 Javascript
简短几句jquery代码的实现一个图片向上滚动切换
2011/09/02 Javascript
使用pjax实现无刷新更改页面url
2015/02/05 Javascript
jquery实现浮动在网页右下角的彩票开奖公告窗口代码
2015/09/04 Javascript
jQuery实现滑动页面固定顶部显示(可根据显示位置消失与替换)
2015/10/28 Javascript
关于Javascript中document.cookie的使用
2017/03/08 Javascript
详解JavaScript中return的用法
2017/05/08 Javascript
解决Jstree 选中父节点时被禁用的子节点也会选中的问题
2017/12/27 Javascript
JS实现运动缓冲效果的封装函数示例
2018/02/18 Javascript
vue实现多条件和模糊搜索功能
2019/05/28 Javascript
Vue 中获取当前时间并实时刷新的实现代码
2020/05/12 Javascript
[01:07:02]DOTA2-DPC中国联赛 正赛 iG vs PSG.LGD BO3 第三场 2月26日
2021/03/11 DOTA
Python 拷贝对象(深拷贝deepcopy与浅拷贝copy)
2008/09/06 Python
学习python类方法与对象方法
2016/03/15 Python
selenium+python实现1688网站验证码图片的截取功能
2018/08/14 Python
在python下读取并展示raw格式的图片实例
2019/01/24 Python
pytorch 模型可视化的例子
2019/08/17 Python
Python如何基于rsa模块实现非对称加密与解密
2020/01/03 Python
python2 对excel表格操作完整示例
2020/02/23 Python
Python爬虫爬取、解析数据操作示例
2020/03/27 Python
Python使用lambda抛出异常实现方法解析
2020/08/20 Python
详解python中的lambda与sorted函数
2020/09/04 Python
bonprix匈牙利:女士、男士和儿童服装
2019/07/19 全球购物
销售职业生涯规划范文
2014/03/14 职场文书
责任胜于能力演讲稿
2014/05/20 职场文书
莫言诺贝尔获奖演讲稿
2014/05/21 职场文书
公司前台接待岗位职责
2015/04/03 职场文书
周一问候语大全
2015/11/10 职场文书
靠谱的活动总结
2019/04/16 职场文书
【超详细】八大排序算法的各项比较以及各自特点
2021/03/31 Python
mysql备份策略的实现(全量备份+增量备份)
2021/07/07 MySQL
修改并编译golang源码的操作步骤
2021/07/25 Golang