首页 > 其他分享 >tkinter的几个例子

tkinter的几个例子

时间:2022-10-08 14:48:10浏览次数:111  
标签:tkinter show 几个 self 例子 result path infile tk

参考这个网站学习Tkinter Text Add Scrollbar design | Python GUI Tutorial-ApiDemos™

 

第一个简单点

from pathlib import Path
# import os
# from time import time, localtime, strftime
from tkinter import Tk, Entry, Button, Listbox, X, Y, END, Scrollbar, RIGHT, BOTTOM, HORIZONTAL, StringVar, Label
# from tkinter.filedialog import askdirectory
from tkinter.filedialog import askopenfile


class MainGUI():

    def __init__(self):
        myWindow = Tk()
        myWindow.title("批量新建文件夹")
        #设置窗口大小
        myWindow.geometry('590x400')
        #增加标签
        self.label_1 = Label(myWindow, text=' 目标文件:')
        self.label_1.place(x=10, y=10, width=70, height=30)
        # self.label_2 = Label(myWindow, text='文件夹数量:')
        # self.label_2.place(x=10, y=50,width=70, height=30)

        #增加文本框
        # addr = StringVar(value='C:\\Users\\xxxx\\Desktop') #文本框默认显示的内容
        addr = StringVar(value='')  #文本框默认显示的内容
        self.input_entry = Entry(myWindow,
                                 highlightcolor='red',
                                 highlightthickness=1,
                                 textvariable=addr)
        self.input_entry.place(x=80, y=10, width=410, height=30)
        self.btn_in = Button(myWindow,
                             text='选择文件',
                             command=self.open_file,
                             width=10,
                             height=1)
        self.btn_in.place(x=500, y=10)

        # folder_quantity = str(
        #     self.get_folder_qty())  #从日志文件`log.txt`中读取最近使用过的文件夹数量
        # def_qty = StringVar(value=folder_quantity)
        # self.folderQty_entry = Entry(myWindow,
        #                              highlightcolor='blue',
        #                              highlightthickness=1,
        #                              textvariable=def_qty)
        # self.folderQty_entry.place(x=80, y=50, width=410, height=30)
        # self.btn_exe = Button(myWindow,
        #                       text='执行新建',
        #                       command=self.create_folders,
        #                       width=10,
        #                       height=1)
        # self.btn_exe.place(x=500, y=50)

        #增加列表框
        self.result_show = Listbox(myWindow, bg='Azure')
        self.result_show.place(x=10, y=50, width=570, height=290)
        self.sbY = Scrollbar(self.result_show,
                             command=self.result_show.yview)  #在列表框中增加Y轴滚动条
        self.sbY.pack(side=RIGHT, fill=Y)
        self.result_show.config(yscrollcommand=self.sbY.set)
        self.sbX = Scrollbar(self.result_show,
                             command=self.result_show.xview,
                             orient=HORIZONTAL)  #在列表框中增加X轴滚动条
        self.sbX.pack(side=BOTTOM, fill=X)
        self.result_show.config(xscrollcommand=self.sbX.set)

        myWindow.mainloop()

    def open_file(self):
        file = askopenfile(mode='r', filetypes=[('txt files', '*.txt')])
        if file is not None:
            # content = file.read()
            # dir_path = Path.cwd()
            # infile_path = dir_path.joinpath('mulu.txt')
            infile_path = Path(file.name)
            dir_path = infile_path.parent

            if infile_path.exists():
                fo = open(infile_path, 'r')
                for line in fo.readlines():
                    line = line.strip()
                    arr = line.split('/')
                    arr2 = arr[-1].split(',')
                    path = arr[0]
                    for i in range(1, len(arr) - 1):
                        path = path + "/" + arr[i]
                        for j in range(len(arr2)):
                            name = arr2[j]
                            full_path = dir_path.joinpath(path).joinpath(name)
                            if not full_path.exists():
                                full_path.mkdir(parents=True, exist_ok=True)
                                ss = f'目录新建成功:{full_path}'
                                self.result_show.insert("end", ss)
                            else:
                                ss = f'目录已经存在:{full_path}'
                                self.result_show.insert("end", ss)

                fo.close()
                ss = f'程序运行完成'
                self.result_show.insert("end", ss)
                print('done')

    # def select_dir1(self):
    #     self.input_entry.delete(0, END)
    #     self.input_entry.insert(0, askdirectory(initialdir="D:\\"))

    # def create_folders(self):
    #     date = self.get_current_date()  #获取日期
    #     qty = int(self.folderQty_entry.get())  #获取文本框中文件夹数量,并转为整数
    #     for i in range(1, qty + 1):
    #         folder = self.input_entry.get() + "\\" + date + '-' + str(i)
    #         # 判断是否已经存在该目录
    #         if not os.path.exists(folder):
    #             # 目录不存在,进行创建操作
    #             os.makedirs(folder)  #使用os.makedirs()方法创建目录
    #             f = f"目录新建成功:{folder}"  # 创建一个显示项
    #             self.result_show.insert("end", f)  #将结果添加到列表框中
    #         else:
    #             f = f"目录已存在:{folder}"  # 创建一个显示项
    #             self.result_show.insert("end", f)  #将结果添加到列表框中
    #     f = "-" * 100  #创建分割线
    #     self.result_show.insert("end", f)  # 将分割线添加到列表框
    #     f = f"程序运行完成,请关闭窗口退出."  # 创建一个显示项
    #     self.result_show.insert("end", f)  # 将结果添加到列表框
    #     f = " " * 100
    #     self.result_show.insert("end", f)  # 将以上空格添加到列表框
    #     self.save_recent_folder_qty()  #保存最新的文件夹数量

    # def get_current_date(self):
    #     time_stamp = time()
    #     local_time = localtime(time_stamp)
    #     str_time_month = int(strftime('%m', local_time))
    #     str_time_day = int(strftime('%d', local_time))
    #     return str(str_time_month) + "." + str(str_time_day)

    # def get_folder_qty(self):
    #     '''从log.txt文件中获取最近的文件夹数量,若没有则返回0'''
    #     log_file = os.getcwd() + "\\log.txt"
    #     if os.path.exists(log_file):
    #         with open(log_file, "r") as f:
    #             qty = f.readline()
    #             return int(qty)
    #     else:
    #         return 0

    # def save_recent_folder_qty(self):
    #     '''保存最近的文件夹数量'''
    #     log_file = os.getcwd() + "\\log.txt"
    #     with open(log_file, "w") as f:
    #         recent_qty = str(self.folderQty_entry.get())
    #         f.write(recent_qty)


if __name__ == '__main__':
    # infile_path=os.getcwd()+'./mulu.txt'
    MainGUI()

第二个多了几个控件

# contact me: [email protected]
import os
# import shutil
import tkinter as tk
from tkinter import filedialog as fd
from tkinter import messagebox as mb
from PIL import Image
from pathlib import Path
from tkinter import Tk, Entry, Button, Listbox, X, Y, END, Scrollbar, RIGHT, BOTTOM, HORIZONTAL, StringVar, Label
# from tkinter.filedialog import askdirectory
from tkinter.filedialog import askopenfile
from tkinter import filedialog as fd
from tkinter import messagebox as mb

inpath = ''


class MainGUI():

    def __init__(self):
        window = tk.Tk()
        window.geometry('600x400')
        window.title('图片批量压缩工具')

        self.label = tk.Label(window, bg='white', width=20, text='是否要保留原文件?')

        var = tk.StringVar()
        var.set('yes')
        self.var = var
        self.r1 = tk.Radiobutton(window, text='是', variable=var, value='yes')
        self.r2 = tk.Radiobutton(window, text='否', variable=var, value='no')
        self.label.place(x=10, y=10, width=120, height=20)
        self.r1.place(x=140, y=10, width=40, height=20)
        self.r2.place(x=180, y=10, width=40, height=20)

        # 增加文本框
        addr = tk.StringVar(value='')  # 文本框默认显示的内容
        self.input_entry = tk.Entry(window,
                                    highlightcolor='red',
                                    highlightthickness=1,
                                    textvariable=addr)
        self.input_entry.place(x=10, y=40, width=410, height=30)
        self.btn_in = tk.Button(window,
                                text='选择目录',
                                command=self.open_directory,
                                width=10,
                                height=1)
        self.btn_in.place(x=400, y=40)
        self.btn_run = tk.Button(
            window, text="运行", command=self.run, width=10, height=1)
        self.btn_run.place(x=500, y=40)

        # # 增加列表框
        self.result_show = tk.Listbox(window, bg='Azure')
        self.result_show.place(x=10, y=100, width=570, height=290)
        self.sbY = tk.Scrollbar(self.result_show,
                                command=self.result_show.yview)  # 在列表框中增加Y轴滚动条
        self.sbX = tk.Scrollbar(self.result_show,
                                command=self.result_show.xview,
                                orient=HORIZONTAL)  # 在列表框中增加X轴滚动条
        self.result_show.config(xscrollcommand=self.sbX.set)
        self.result_show.config(yscrollcommand=self.sbY.set)
        self.sbX.pack(side=BOTTOM, fill=X)
        self.sbY.pack(side=RIGHT, fill=Y)
        # self.result_show = tk.Text(
        #     window, wrap='none', bg='lightyellow')
        # x_scrollbar = tk.Scrollbar(window, orient=HORIZONTAL)
        # y_scrollbar = tk.Scrollbar(window)
        # x_scrollbar.pack(side=BOTTOM, fill=X)
        # y_scrollbar.pack(side=RIGHT, fill=Y)
        # self.result_show.pack(fill=tk.BOTH, expand=True)
        # x_scrollbar.config(command=self.result_show.xview)
        # y_scrollbar.config(command=self.result_show.yview)
        # self.result_show.config(xscrollcommand=x_scrollbar.set)
        # self.result_show.config(yscrollcommand=y_scrollbar.set)

        window.mainloop()

    def run(self):
        global inpath
        schoose = self.var.get()
        if inpath:
            self.resizePics(inpath, schoose)

    def open_directory(self):
        global inpath
        inpath = fd.askdirectory()
        if inpath:
            self.input_entry.insert(0, inpath)

    def open_file(self):
        file = askopenfile(mode='r', filetypes=[('txt files', '*.txt')])
        if file is not None:
            # content = file.read()
            # dir_path = Path.cwd()
            # infile_path = dir_path.joinpath('mulu.txt')
            infile_path = Path(file.name)
            dir_path = infile_path.parent

            if infile_path.exists():
                fo = open(infile_path, 'r')
                for line in fo.readlines():
                    line = line.strip()
                    arr = line.split('/')
                    arr2 = arr[-1].split(',')
                    path = arr[0]
                    for i in range(1, len(arr) - 1):
                        path = path + "/" + arr[i]
                        for j in range(len(arr2)):
                            name = arr2[j]
                            full_path = dir_path.joinpath(path).joinpath(name)
                            if not full_path.exists():
                                full_path.mkdir(parents=True, exist_ok=True)
                                ss = f'目录新建成功:{full_path}'
                                self.result_show.insert("insert", ss)
                                self.result_show.update()
                            else:
                                ss = f'目录已经存在:{full_path}'
                                self.result_show.insert("insert", ss)
                                self.result_show.update()

                fo.close()
                ss = f'程序运行完成'
                self.result_show.insert("end", ss)
                print('done')

    def resizePics(self, inpath, schoose):
        exts = ['.jpg', '.jpeg', '.png']

        in_path = Path(inpath)
        out_path = in_path.with_name(in_path.stem + '-resize')
        if not out_path.exists():
            out_path.mkdir()
        # out_path=in_path.parent / (in_path.stem+'-resize')

        size = (800, 600)

        # print("picture resizing is processing,pleae wait...")
        for root, dirs, files in os.walk(in_path):

            inroot_path = Path(root)
            outroot_path = out_path.joinpath(inroot_path.relative_to(in_path))
            if not outroot_path.exists():
                outroot_path.mkdir()

            for file in files:
                infile_path = Path(root).joinpath(file)
                ext2 = infile_path.suffix
                ext = ext2.lower()
                if ext in exts:
                    outfile_path = outroot_path / file
                    try:
                        # print('processing')
                        im = Image.open(infile_path)
                        if im.size[0] > 800:
                            im.thumbnail(size)
                            im.save(outfile_path, "jpeg")
                            im.close()
                            if schoose == 'yes':
                                print('{} is resized'.format(infile_path))
                                ss = f'{infile_path} is resized'
                                self.result_show.insert("end", ss)
                                self.result_show.update()
                                tk.after(1000)
                            else:
                                infile_path.unlink()
                                print('{} is resized and deleted'.format(
                                    infile_path))
                                ss = f'{infile_path} is resized and deleted'
                                self.result_show.insert("end", ss)
                                self.result_show.update()
                                tk.after(1000)
                        else:
                            print('{} is skipped'.format(infile_path))
                            ss = f'{infile_path} is skipped'
                            self.result_show.insert("end", ss)
                            self.result_show.update()
                            tk.after(1000)

                    except Exception as e:
                        print(e)
                        pass
        mb.showinfo('提示', '批量处理已完成!')


if __name__ == '__main__':
    gui = MainGUI()

 

标签:tkinter,show,几个,self,例子,result,path,infile,tk
From: https://www.cnblogs.com/dogingate/p/16768847.html

相关文章