import wx
import pandas as pd
import os
import time
class FrmMain(wx.Frame):
"""窗体"""
def __init__(self,parent,id,title):
super(FrmMain, self).__init__(parent=None,id=-1,title=title,
style = wx.CAPTION|wx.MINIMIZE_BOX|wx.CLOSE_BOX,size = (800,500))
self.Center()
panel = wx.Panel(self)
self.text_select =wx.TextCtrl(panel,value = "")
self.text_select.Bind(wx.EVT_TEXT,self.OnTextCtrlState)
self.bt_select =wx.Button(panel,label = "选择Excel文件",size = (90,25))
self.bt_select.Bind(wx.EVT_BUTTON,self.OnOpen) #绑定选择文件事件
self.text_path =wx.TextCtrl(panel,value = "")
self.text_path.Bind(wx.EVT_TEXT,self.OnTextCtrlState)
self.bt_path =wx.Button(panel,label = "设置保存路径",size = (90,25))
self.bt_path.Disable()
self.bt_path.Bind(wx.EVT_BUTTON,self.OnSetPath) #绑定设置默认路径事件
self.bt_defpath =wx.Button(panel,label = "...",size = (25,25))
self.bt_defpath.Bind(wx.EVT_BUTTON,self.OnSaveAs) #绑定另存为自定义保存路径事件
self.bt_confirm =wx.Button(panel,label = "执行")
self.bt_confirm.Disable() #设置初始默认按钮不可点击(灰色)
self.bt_confirm.Bind(wx.EVT_BUTTON,self.OnClickSubmit) #绑定确认事件
self.bt_cancel =wx.Button(panel,label = "关闭")
self.bt_cancel.SetDefault() #设置默认按钮,接收键盘Enter
self.bt_cancel.Bind(wx.EVT_BUTTON,self.OnExit) #绑定退出事件
self.bt_reset =wx.Button(panel,label = "重置")
self.bt_reset.Bind(wx.EVT_BUTTON,self.OnClickReset) #绑定重置事件
self.bt_open =wx.Button(panel,label = "打开文件夹")
self.bt_open.Disable()
self.bt_open.Bind(wx.EVT_BUTTON,self.OnClickOpenRes) #绑定打开文件夹事件
# 添加BoxSizer,横向(使用BoxSizer,控件相对位置,窗口最大化时按钮跟随变化)
hsizer_select = wx.StaticBoxSizer(wx.HORIZONTAL,panel,label = "Excel文件选择") #静态StaticBoxSizer带标题和环线
hsizer_select.Add(self.bt_select,proportion = 0,flag = wx.ALL,border = 5) #proportion = 0表示定长
hsizer_select.Add(self.text_select,proportion = 1,flag = wx.ALL,border = 5)
hsizer_path = wx.StaticBoxSizer(wx.HORIZONTAL,panel,label = "保存路径设置")
hsizer_path.Add(self.bt_path,proportion = 0,flag = wx.ALL,border = 5)
hsizer_path.Add(self.text_path,proportion = 1,flag = wx.ALL,border = 5)
hsizer_path.Add(self.bt_defpath,proportion = 0,flag = wx.ALL,border = 5)
hsizer_cmd = wx.BoxSizer(wx.HORIZONTAL)
hsizer_cmd.Add(self.bt_confirm,proportion = 1,flag = wx.ALIGN_CENTER,border = 5)
hsizer_cmd.AddSpacer(10) #各控件间添加固定大小的空白间隔
hsizer_cmd.Add(self.bt_open,proportion = 1,flag = wx.ALIGN_CENTER,border = 5)
hsizer_cmd.AddSpacer(10)
hsizer_cmd.Add(self.bt_reset,proportion = 1,flag = wx.ALIGN_CENTER,border = 5)
hsizer_cmd.AddSpacer(10)
hsizer_cmd.Add(self.bt_cancel,proportion = 1,flag = wx.ALIGN_CENTER,border = 5)
# 添加BoxSizer,纵向
vsizer_all = wx.BoxSizer(wx.VERTICAL)
vsizer_all.Add(hsizer_select,proportion = 1,flag = wx.EXPAND|wx.LEFT|wx.RIGHT,border = 10)
vsizer_all.Add(hsizer_path,proportion = 1,flag = wx.EXPAND|wx.LEFT|wx.RIGHT,border = 10)
vsizer_all.Add(hsizer_cmd,proportion = 1,flag = wx.EXPAND|wx.LEFT|wx.RIGHT,border = 10)
panel.SetSizer(vsizer_all)
self.CreateStatusBar() #创建一个状态栏
self.StatusBar.SetFieldsCount(number = 2)
self.SetStatusWidths([-1,35])
self.StatusBar.SetStatusText("Welcome to Changer!Version 2.0",0)
#关闭
def OnExit(self, event):
"""退出程序"""
# wx.Exit()
self.Close(True)
# 确认
def OnClickSubmit(self,event):
"""单击确定执行此方法"""
#读取数据
self.timeCount = 0
self.timer.Start(1000) # 1 second interval(1秒间隔,默认是ms)
self.StatusBar.SetStatusText("读取数据...",0)
df_res = pd.DataFrame() #定义一个空白DataFrame
type_res = os.path.splitext(fileName[0])[1]
if type_res == ".txt":
for filePath in fileName:
df = pd.read_table(filePath, encoding="gbk", engine = "python", header = 0)
df_res = df_res.append(df, ignore_index=True, sort=False)
elif type_res == ".csv":
for filePath in fileName:
df = pd.read_csv(filePath, encoding="gbk", engine = "python", header = 0)
df_res = df_res.append(df, ignore_index=True, sort=False)
elif type_res == ".xlsx" or type_res == ".xls":
for filePath in fileName:
df_dict = pd.read_excel(filePath, sheet_name = None, encoding="gbk", header = 0)
for df in df_dict:
df_res = df_res.append(df_dict[df], ignore_index=True, sort=False)
else:
self.timer.Stop()
wx.MessageBox("不支持该类型文件!")
self.timer.Stop()
#写入数据
# self.timeCount = 0
# self.timer.Start(1000)
self.StatusBar.SetStatusText("写入数据...",0)
file_name = self.text_path.GetValue()
sType = os.path.splitext(file_name)[1]
if os.path.exists(os.path.dirname(file_name)) ==True:
if sType == ".csv" or sType == ".txt":
try:
df_res.to_csv(file_name, encoding="gbk",index=0)
self.timer.Stop()
wx.MessageBox("汇聚完成!")
self.bt_open.Enable()
self.bt_open.SetDefault()
except Exception as e:
pass
elif sType == ".xlsx" or sType == ".xls":
try:
df_res.to_excel(file_name, encoding="gbk",index=0)
self.timer.Stop()
wx.MessageBox("汇聚完成!")
self.bt_open.Enable()
self.bt_open.SetDefault()
except Exception as e:
pass
else:
self.timer.Stop()
wx.MessageBox("文件类型错误!\n允许保存为.csv;.xlsx;.xls")
else:
self.timer.Stop()
wx.MessageBox("文件保存路径存在异常!")
self.StatusBar.SetStatusText("Welcome to Changer!Version 2.0",0)
# 打开文件夹
def OnClickOpenRes(self,event):
"""单击打开文件夹执行此方法"""
# resPath = os.path.split(self.text_path.GetValue())[0]
resPath = os.path.dirname(self.text_path.GetValue())
if os.path.exists(os.path.dirname(resPath)) ==True:
try:
os.system("explorer.exe /n, "+ resPath) #其中/n一定不能少
except Exception as e:
pass
else:
wx.MessageBox("路径不存在!")
#文本框状态
def OnTextCtrlState(self,event):
"""文本框状态监听"""
if self.text_select.GetValue() !="" and self.text_path.GetValue() != "":
self.bt_confirm.Enable()
self.bt_confirm.SetDefault() # self.bt_reset.SetFocus() 也可获得焦点,但有虚线框
else:
self.bt_confirm.Disable()
# 重置
def OnClickReset(self,event):
"""单击重置执行此方法"""
self.text_select.SetValue("")
self.text_path.SetValue("")
self.bt_path.Disable()
self.bt_confirm.Disable()
self.bt_open.Disable()
# 打开文件选择对话框
def OnOpen(self, event):
with wx.FileDialog(self, "Open Excel Files",pos=wx.DefaultPosition,wildcard="CSV 文件(*.csv)|*.csv|Excel 文件(*.xlsx;*.xls)|*.xlsx;*.xls|txt 文件(*.txt)|*.txt",
style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.FD_MULTIPLE) as fileDialog:
if fileDialog.ShowModal() == wx.ID_CANCEL:
return # 用户点了取消按钮
global defPath, fileName
defPath = fileDialog.GetDirectory() #获取目录
fileName = fileDialog.GetPaths() #获取目录及文件名
str_fileName = ";".join(fileName)
self.text_select.SetValue(str_fileName)
self.bt_path.Enable()
# 设置默认保存路径
def OnSetPath(self, event):
t_write = time.strftime("%y%m%d%H%M%S", time.localtime())
ftype = os.path.splitext(fileName[0])[1] #取第一个文件的扩展名
if ftype == ".txt":
ftype = ".csv"
fname = os.path.splitext(fileName[0])[0].split("\\")[-1] + "_" + t_write + ftype
defFileName = os.path.join(defPath,fname)
self.text_path.SetValue(defFileName)
#另存为(自定义保存路径)
def OnSaveAs(self, event):
t_save = time.strftime("%y%m%d%H%M%S", time.localtime())
defFile = os.path.splitext(fileName[0])[0].split("\\")[-1] + "_" + t_save
with wx.FileDialog(self, "另存为", defaultFile = defFile, wildcard="CSV 文件(*.csv)|*.csv|Excel 文件(*.xlsx)|*.xlsx",
style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as fileDialog:
if fileDialog.ShowModal() == wx.ID_CANCEL:
return # 用户点了取消按钮
uFileName = fileDialog.GetPath()
self.text_path.SetValue(uFileName)
if __name__ == "__main__":
app = wx.App()
frm = FrmMain(parent=None,id=-1,title="参数查询工具")
frm.Show()
app.MainLoop()
wxPython设计GUI窗体
使用wxPython创建GUI界面
最新推荐文章于 2024-08-14 09:50:19 发布
本文介绍了如何利用Python的wxPython库设计图形用户界面(GUI)窗体,讲解了相关组件的使用和布局管理,帮助开发者构建桌面应用程序。
619

被折叠的 条评论
为什么被折叠?



