使用Python tkinter開發一個文件/文件夾批處理對話框工具

一、工具效果圖

 

二、使用的原理方法

界面:Python  tkinter

日誌傳輸:UDP Socket 

 

三、源碼

操作系統:Windows 10

開發環境:Python 3.6

3.1 main.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
import os
import sys
import getopt
import threading
import socket
import traceback
import random

import log
from log import LOG_PRINTF
from testrun import TESTRun
from tkinter import *
from tkinter import filedialog

class App:

    def __init__(self, master):
        self.master = master
        self.initWidgets()
        self.log_thread_status=1
        self.th_log = threading.Thread(target=self.log_thread, name="log_thread")
        self.th_log.setDaemon(True)
        self.th_log.start()

        self.th_run=None;


    def initWidgets(self):
        self.label_input = Label(self.master, text="輸入文件", width=10, height=1);
        self.label_input.place(x=5, y=5);
        self.entry_input = Entry(self.master,
                               width=40,
                               font=('StSong', 14))
        self.entry_input.place(x=100, y=5);

        self.button_input = Button(self.master, text='...', width=5,command=self.open_inputbutton)
        self.button_input.place(x=480, y=5)

        self.button_run = Button(self.master, text='run', width=5,command=self.open_runbutton)
        self.button_run.place(x=540, y=45)

        self.text_log=Text(self.master,width=72,height=16,
                               font=('StSong', 12))
        self.text_log.place(x=5, y=80)

    def open_inputbutton(self):
        print("open_inputbutton")
        #self.filepath = filedialog.askdirectory(title='圖片文件夾')
        self.filepath = filedialog.askopenfilename(title='file')
        print(self.filepath)

        self.entry_input.delete(0, "end")
        self.entry_input.insert(0,self.filepath)
        logstr=self.filepath+'\n'
        self.text_log.insert(INSERT,logstr)


    def open_runbutton(self):
        print("open_runbutton")
       # logstr =  'run...\n'
        #self.text_log.insert(INSERT, logstr)
        #log.LOG_PRINTF(logstr)
        if self.th_run != None:
            self.th_run.join()
        self.th_run = threading.Thread(target=self.run_thread, name="run_thread")
        self.th_run.setDaemon(True)
        self.th_run.start()

    def log_thread(self):
        print('log_thread...')
        var = 1

        BUFSIZE = 1024
        reconcnt=0;
        port=log.port
        ip_port=None
        while reconcnt <= log.PORTCNT:
            try:
                rnd = random.randint(1, log.PORTCNT)
                log.port=port+rnd
                ip_port = (log.ip, log.port)
                print(ip_port)
                reconcnt = reconcnt+1;
                udp_server_client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                udp_server_client.bind(ip_port)

            except Exception as e:
                print(str(e))
                print("reconcnt : "+str(reconcnt));
                continue
            else:
                break

        if reconcnt > log.PORTCNT:
            self.text_log.insert(INSERT, "LOG UDP SOCKET OPEN ERROR , MAX :"+str(log.PORTCNT))
            return ;
        logstr = "LOG service "+str(ip_port)+"  Init OK\n";
        self.text_log.insert(INSERT, logstr)
        while self.log_thread_status == 1:
            msg, addr = udp_server_client.recvfrom(BUFSIZE)
            ret = str(msg, encoding="utf-8")
            print(ret)
            #udp_server_client.sendto(msg.upper(), addr)
            logstr=ret
            self.text_log.insert(INSERT, logstr)
    def exit(self):
        self.log_thread_status = 0;

    def run_thread(self):
        self.srcfile=self.entry_input.get();
        if not os.path.exists(self.srcfile):

            LOG_PRINTF('['+self.srcfile+']'+"  file not exists\n")
            return ;
           (filepath, tempfilename) = os.path.split(self.srcfile);
        (shotname, extension) = os.path.splitext(tempfilename);
        dstfilename=shotname+'_out'+extension   #".txt"
        self.dstfile=os.path.join(filepath,dstfilename)
        mobj = TESTRun(self.srcfile,self.dstfile);
        mobj.run();
        LOG_PRINTF("Run Finish!!!\n")


if __name__ == '__main__':
    # 初始化Tk()
    myWindow = Tk()
    # 設置標題
    myWindow.title(r'Python GUI Learning')
    # 設置窗口大小
    width = 600
    height = 400
    # 獲取屏幕尺寸以計算佈局參數,使窗口居屏幕中央
    screenwidth = myWindow.winfo_screenwidth()
    screenheight = myWindow.winfo_screenheight()
    alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
    myWindow.geometry(alignstr)
    # 設置窗口是否可變長、寬,True:可變,False:不可變
    myWindow.resizable(width=False, height=True)
    mapp=App(myWindow);
    # 進入消息循環
    myWindow.mainloop()





 

3.2 log.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket
global ip
global port
global PORTCNT
ip='127.0.0.1'
port=19000
PORTCNT=100


BUFSIZE=1024
udp_server_client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

def LOG_PRINTF(str):
    msg=str;
    try:
        ip_port=(ip,port)
        print(ip_port)
        udp_server_client.sendto(msg.encode('utf-8'),ip_port)
    except Exception as e:
        print(str(e))
#    back_msg,addr=udp_server_client.recvfrom(BUFSIZE)
#    print(back_msg.decode('utf-8'),addr)

 

3.3 testrun.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from log import LOG_PRINTF
class TESTRun:
    def __init__(self, srcfile,dstfile):
        self.srcfile=srcfile;
        self.dstfile=dstfile;

    def run(self):
        LOG_PRINTF(">>>run ")
        LOG_PRINTF("SRC: " + self.srcfile + "\n")
        LOG_PRINTF("DST: " + self.dstfile + "\n")
        dstfd = open(self.dstfile, 'wt', encoding='UTF-8')
        if dstfd == None:
            return;
        with open(self.srcfile, 'rt', encoding='UTF-8') as fd:
            for line in fd:
                print(line)
                '''
                ....
                
                '''

                dstfd.write(line + '\n')

        fd.close();
        dstfd.close();

 

3.4 README.md

最大軟件同時運行數量: 100個
UDP端口占用 19000~19100

 

三、測試效果

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章