tkinter实例
import tkinter as tk
import hashlib
import time
LOG_LINE_NUM = 0
class MY_GUI():
def __init__(self, init_window_name):
self.init_window_name = init_window_name
# 设置窗口
def set_init_window(self):
self.init_window_name.title("测试工具") # 窗口名
self.init_window_name.geometry('1068x681+10+10') # 窗口大小
# 标签
self.init_data_label = tk.Label(self.init_window_name, text="待处理数据", fg='red')
self.init_data_label.grid(row=0, column=0)
self.result_data_label = tk.Label(self.init_window_name, text="输出结果", fg='red')
self.result_data_label.grid(row=0, column=12)
self.log_label = tk.Label(self.init_window_name, text="日志", fg='red')
self.log_label.grid(row=12, column=0)
# 文本框
# foreground 设置text里面的字体颜色
self.init_data_Text = tk.Text(self.init_window_name, width=67, height=35, foreground='blue') # 原始数据录入框
self.init_data_Text.grid(row=1, column=0, rowspan=10, columnspan=10)
self.result_data_Text = tk.Text(self.init_window_name, width=70, height=49, foreground='green') # 处理结果展示
self.result_data_Text.grid(row=1, column=12, rowspan=15, columnspan=10)
self.log_data_Text = tk.Text(self.init_window_name, width=66, height=9, foreground='red') # 日志框
self.log_data_Text.grid(row=13, column=0, columnspan=10)
# 按钮
self.str_trans_to_md5_button = tk.Button(self.init_window_name, text="字符串转MD5", bg="lightblue", width=10,
command=self.str_trans_to_md5) # 调用内部方法 加()为直接调用
self.str_trans_to_md5_button.grid(row=1, column=11)
# 功能函数
def str_trans_to_md5(self):
src = self.init_data_Text.get(1.0, tk.END).strip().replace("\n", "").encode()
# print("src =",src)
if src:
try:
myMd5 = hashlib.md5()
myMd5.update(src)
myMd5_Digest = myMd5.hexdigest()
# print(myMd5_Digest)
# 输出到界面
self.result_data_Text.delete(1.0, tk.END)
self.result_data_Text.insert(1.0, myMd5_Digest)
self.write_log_to_Text("INFO:str_trans_to_md5 success")
except:
self.result_data_Text.delete(1.0, tk.END)
self.result_data_Text.insert(1.0, "字符串转MD5失败")
else:
self.write_log_to_Text("ERROR:str_trans_to_md5 failed")
# 获取当前时间
def get_current_time(self):
current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
return current_time
# 日志动态打印
def write_log_to_Text(self, logmsg):
global LOG_LINE_NUM
current_time = self.get_current_time()
logmsg_in = str(current_time) + " " + str(logmsg) + "\n" # 换行
if LOG_LINE_NUM <= 7:
self.log_data_Text.insert(tk.END, logmsg_in)
LOG_LINE_NUM = LOG_LINE_NUM + 1
else:
self.log_data_Text.delete(1.0, 2.0)
self.log_data_Text.insert(tk.END, logmsg_in)
def gui_start():
root = tk.Tk() # 实例化出一个父窗口
# bm1 = tk.PhotoImage(file='11.gif') # 实例化一个图片
run = MY_GUI(root)
# 设置根窗口默认属性
run.set_init_window()
root.mainloop() # 父窗口进入事件循环,可以理解为保持窗口运行,否则界面不展示
if __name__ == '__main__':
gui_start()
效果截图: