1.導入tkinter模塊
import Tkinter
2.創建控件並啟動
root = Tkinter.Tk()
root.title('設置窗口標題') # 設置窗口標題
# 進入消息循環
root.mainloop()
3.在界面上添加常用組件
a = Label(root, text='test_message') #標簽控件,顯示文本
a.pack() #將控件綁定到界面上
b = Entry(self.root, width=80) #輸入控件;用於顯示簡單的文本內容
b.get() #獲取界面上輸入的內容
c = Button(self.root, text='點擊', command=function_name) #按鈕控件;在程序中顯示按鈕,可以綁定一個方法,點擊按鈕就調用該方法
d = Listbox(self.root, width=150) #列表框控件;在Listbox窗口小部件是用來顯示一個字符串列表給用戶
d.insert(0, 'test_message') #往列表框指定位置插入一個字符串
#其他控件請查看源文檔
4.應用示例-自動清理日志的小工具
import os import datetime import time from tkinter import * import nnlog log = nnlog.Logger('delete_file.log', when='D') class Application(): def __init__(self): self.root = Tk() self.createWidgets() def createWidgets(self): self.a= Label(self.root, text='輸入待刪除日志的路徑') self.b= Label(self.root, text='請謹慎輸入,將會刪除該路徑下符合要求的所有日志文件,包括文件夾下的') self.a.pack() self.b.pack() self.logPathInput = Entry(self.root, width=80) self.logPathInput.pack() self.c = Label(self.root, text='輸入日志文件后綴,默認為.log') self.c.pack() self.logNameInput = Entry(self.root, width=80) self.logNameInput.pack() self.c = Label(self.root, text='輸入多少天之前的日志,不輸入則默認刪除五天前的') self.c.pack() self.deleTimeInput = Entry(self.root, width=80) self.deleTimeInput.pack() self.alertButton = Button(self.root, text='開始刪除', command=self.del_log_file) self.alertButton.pack() self.resText = Listbox(self.root, width=80) self.resText.pack() def del_log_file(self): """刪除指定路徑下超過X天的日志文件 """ path = self.logPathInput.get() del_time = self.deleTimeInput.get() if self.deleTimeInput.get() else 5 log_name=self.logNameInput.get() if self.logNameInput.get() else '.log' if del_time and log_name and os.path.exists(path): self.resText.insert(0, '刪除日志文件如下') self.resText.insert(0, '.............開始刪除日志文件,退出請直接關閉工具..........') for cur_path, cur_dirs, cur_files in os.walk(path): for log_file in cur_files: if log_file.endswith(log_name): # file_time_stamp = log_file.split(".")[0].split("_")[1] # 獲取文件修改時間,時間戳格式 filePath = os.path.join(cur_path, log_file) filetime_stamp = os.path.getmtime(filePath) # 獲取當前時間 today = datetime.datetime.now() # 計算偏移量,前X天 offset = datetime.timedelta(days=-int(del_time)) print(offset) # 獲取想要的日期的時間,即前X天時間 re_date = (today + offset) # 前3天時間轉換為時間戳 re_date_unix = time.mktime(re_date.timetuple()) try: if filetime_stamp <= re_date_unix: self.resText.insert(2, filePath) os.remove(filePath) log.debug('刪除文件成功:' + filePath) print(filePath) except: continue self.resText.insert(1, '....................掃描完畢,等待下次運行...............') #10000ms后再次調用刪除日志的函數 self.root.after(86400000,self.del_log_file) else: self.resText.insert(0, 'error:輸入的文件夾不存在') self.resText.insert(0, '******************************************************') if __name__ == "__main__": app = Application() # 設置窗口標題: app.root.title('自動清理日志') # 主消息循環: app.root.mainloop()
