目标:
- 从零开始使用tkinter组件实现应用程序的简单布局,如:文本框、目录选择框、按钮
- 了解tkinter组件创建和属性配置,以及事件处理,如:显示文本、文本颜色、边框大小/颜色
- 了解tkinter布局方式,如:grid、pack
-
了解工具库的使用,如:clipboard、python-docx
需要实现的应用效果,如下图所示:
应用实现过程
- 引入程序依赖的软件包
import os
import tkinter as tk
from tkinter import filedialog, scrolledtext
from docx import Document
import clipboard
- 定义应用程序实现类
class Demo:
def __init__(self, gui):
self.gui = gui
self.initLoad()
def initLoad(self):
i = 0
self.srcLabel = tk.Label(self.gui, text='待合并文件目录:', bg='#3E4149')
self.srcLabel.grid(row=i, column=0, padx=(10, 0))
self.srcDirText = tk.StringVar()
self.srcEntry = tk.Entry(self.gui, textvariable=self.srcDirText, width=20, state='readonly')
self.srcEntry.grid(row=i, column=1, pady=(10, 0), padx=(0, 10))
self.btnSrcDir = tk.Button(self.gui, text='选择目录', bg='#3E4149', command=self.choose_src_dir)
self.btnSrcDir.grid(row=i, column=2, pady=(10, 0))
self.dstLabel = tk.Label(self.gui, text='输出目录:', bg='#3E4149')
self.dstLabel.grid(row=i+1, column=0)
self.dstDirText = tk.StringVar()
self.dstntry = tk.Entry(self.gui, textvariable=self.dstDirText, width=20, state='readonly')
self.dstntry.grid(row=i+1, column=1, pady=(10, 0), padx=(0, 10))
self.btnDstDir = tk.Button(self.gui, text='选择目录', bg='#3E4149', command=self.choose_dst_dir)
self.btnDstDir.grid(row=i+1, column=2, pady=(10, 0))
self.progressLabel = tk.Label(self.gui, text='进度:', anchor=tk.E, bg='#3E4149')
self.progressLabel.grid(row = i+2, column=0)
self.btn = tk.Button(gui, text='开始合并', bg='#3E4149', command=self.on_start)
self.btn.grid(row=i+3, column=2)
self.docInfo = tk.Label(self.gui, text='文件基本信息:', bg='#3E4149')
self.docInfo.grid(row=i+4, column=0)
self.scr = scrolledtext.ScrolledText(self.gui, width=80, height=10, fg='white', bg='#3E4149', state='disabled')
self.scr.vbar.configure(width=4)
self.scr.grid(row=i+5, column=0, columnspan=3, pady=(10,10), padx=(10,10))
def on_start(self):
self.doc = Document("mini2.docx")
self.scr['state'] = 'normal'
for table in self.doc.tables:
title = table.cell(0,1)
titleKey = title.text.strip()
self.scr.insert(tk.END, titleKey + '\n')
self.scr.see(tk.END)
self.scr['state'] = 'disabled'
text = self.scr.get(1.0, tk.END)
clipboard.copy(text)
def choose_src_dir(self):
sourceDir = filedialog.askdirectory(title='请选择待合并文件目录', initialdir='.')
self.srcDirText.set(sourceDir)
def choose_dst_dir(self):
dstDir = filedialog.askdirectory(title='请选择输出目录', initialdir='.')
self.dstDirText.set(dstDir)
- 调用应用程序实现类
if __name__ == '__main__':
gui = tk.Tk()
gui.geometry('600x300')
gui.title = "demo"
gui.configure(bg='#3E4149')
app = Demo(gui)
gui.mainloop()