在本文中,我们将介绍如何使用 Python创建一个简单的 GUI 应用程序,该程序允许用户选择保存路径、创建文件夹、输入 HTML 代码并将其保存为 HTML 文件。我们还将添加保存和加载设置的功能,使得用户可以在不同的会话之间保持配置。
C:\pythoncode\new\htmlcodesavetolocalfile.py
结果如下
全部代码
import wx
import os
import xml.etree.ElementTree as ET
import datetime
class MyApp(wx.App):
def OnInit(self):
self.frame = MyFrame(None, title="HTML File Generator")
self.frame.Show()
return True
class MyFrame(wx.Frame):
def __init__(self, parent, title):
super().__init__(parent, title=title, size=(600, 400))
panel = wx.Panel(self)
vbox = wx.BoxSizer(wx.VERTICAL)
# Path selection
hbox1 = wx.BoxSizer(wx.HORIZONTAL)
self.path_txt = wx.TextCtrl(panel)
path_btn = wx.Button(panel, label="选择")
path_btn.Bind(wx.EVT_BUTTON, self.on_select_path)
hbox1.Add(self.path_txt, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
hbox1.Add(path_btn, flag=wx.EXPAND|wx.ALL, border=5)
# Folder name input
hbox2 = wx.BoxSizer(wx.HORIZONTAL)
self.folder_txt = wx.TextCtrl(panel, style=wx.TE_CENTER)
create_folder_btn = wx.Button(panel, label="创建")
create_folder_btn.Bind(wx.EVT_BUTTON, self.on_create_folder)
hbox2.Add(self.folder_txt, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
hbox2.Add(create_folder_btn, flag=wx.EXPAND|wx.ALL, border=5)
# HTML code input
hbox3 = wx.BoxSizer(wx.HORIZONTAL)
self.html_txt = wx.TextCtrl(panel, style=wx.TE_MULTILINE)
hbox3.Add(self.html_txt, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
# HTML file name input
hbox4 = wx.BoxSizer(wx.HORIZONTAL)
self.html_filename_txt = wx.TextCtrl(panel, style=wx.TE_CENTER)
save_html_btn = wx.Button(panel, label="保存")
save_html_btn.Bind(wx.EVT_BUTTON, self.on_save_html)
hbox4.Add(self.html_filename_txt, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
hbox4.Add(save_html_btn, flag=wx.EXPAND|wx.ALL, border=5)
# Batch record selection
hbox5 = wx.BoxSizer(wx.HORIZONTAL)
self.batch_choice = wx.Choice(panel)
load_batch_btn = wx.Button(panel, label="加载记录")
load_batch_btn.Bind(wx.EVT_BUTTON, self.on_load_batch)
hbox5.Add(self.batch_choice, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
hbox5.Add(load_batch_btn, flag=wx.EXPAND|wx.ALL, border=5)
# Save settings button
hbox6 = wx.BoxSizer(wx.HORIZONTAL)
save_settings_btn = wx.Button(panel, label="保存设置")
save_settings_btn.Bind(wx.EVT_BUTTON, self.on_save_settings)
hbox6.Add(save_settings_btn, flag=wx.EXPAND|wx.ALL, border=5)
vbox.Add(hbox1, flag=wx.EXPAND)
vbox.Add(hbox2, flag=wx.EXPAND)
vbox.Add(hbox3, proportion=1, flag=wx.EXPAND)
vbox.Add(hbox4, flag=wx.EXPAND)
vbox.Add(hbox5, flag=wx.EXPAND)
vbox.Add(hbox6, flag=wx.EXPAND)
panel.SetSizer(vbox)
self.Bind(wx.EVT_SHOW, self.on_show)
def on_select_path(self, event):
with wx.DirDialog(self, "选择保存路径", style=wx.DD_DEFAULT_STYLE) as dialog:
if dialog.ShowModal() == wx.ID_OK:
self.path_txt.SetValue(dialog.GetPath())
def on_create_folder(self, event):
path = self.path_txt.GetValue()
folder_name = self.folder_txt.GetValue()
if path and folder_name:
full_path = os.path.join(path, folder_name)
os.makedirs(full_path, exist_ok=True)
wx.MessageBox(f"文件夹 {folder_name} 创建成功", "提示", wx.OK | wx.ICON_INFORMATION)
else:
wx.MessageBox("请先选择保存路径并输入文件夹名称", "错误", wx.OK | wx.ICON_ERROR)
def on_save_html(self, event):
path = self.path_txt.GetValue()
folder_name = self.folder_txt.GetValue()
html_code = self.html_txt.GetValue()
html_filename = self.html_filename_txt.GetValue() + ".html"
if path and folder_name and html_code and html_filename:
full_path = os.path.join(path, folder_name, html_filename)
with open(full_path, "w", encoding="utf-8") as file:
file.write(html_code)
wx.MessageBox(f"HTML 文件 {html_filename} 保存成功", "提示", wx.OK | wx.ICON_INFORMATION)
else:
wx.MessageBox("请确保所有输入框都已填满", "错误", wx.OK | wx.ICON_ERROR)
def on_load_batch(self, event):
batch_name = self.batch_choice.GetStringSelection()
if batch_name:
tree = ET.parse('settings.xml')
root = tree.getroot()
batch = root.find(f"batch[@name='{batch_name}']")
if batch is not None:
self.path_txt.SetValue(batch.find('path').text)
self.folder_txt.SetValue(batch.find('folder').text)
self.html_txt.SetValue(batch.find('html').text)
self.html_filename_txt.SetValue(batch.find('filename').text)
def on_save_settings(self, event):
self.save_settings()
def save_settings(self):
path = self.path_txt.GetValue()
folder_name = self.folder_txt.GetValue()
html_code = self.html_txt.GetValue()
html_filename = self.html_filename_txt.GetValue()
batch_name = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
if os.path.exists("settings.xml"):
tree = ET.parse("settings.xml")
root = tree.getroot()
else:
root = ET.Element("settings")
batch = ET.SubElement(root, "batch", name=batch_name)
ET.SubElement(batch, "path").text = path
ET.SubElement(batch, "folder").text = folder_name
ET.SubElement(batch, "html").text = html_code
ET.SubElement(batch, "filename").text = html_filename
tree = ET.ElementTree(root)
tree.write("settings.xml", encoding="utf-8", xml_declaration=True)
wx.MessageBox("设置已保存", "提示", wx.OK | wx.ICON_INFORMATION)
self.update_batch_choice()
def update_batch_choice(self):
if os.path.exists("settings.xml"):
tree = ET.parse("settings.xml")
root = tree.getroot()
batch_names = [batch.attrib['name'] for batch in root.findall('batch')]
self.batch_choice.Clear()
self.batch_choice.AppendItems(batch_names)
def on_show(self, event):
self.update_batch_choice()
if __name__ == "__main__":
app = MyApp()
app.MainLoop()
1. 安装 wxPython
首先,我们需要安装 wxPython 库。你可以使用 pip 来安装:
pip install wxPython
2. 创建基本框架
我们将创建一个基本的 Python应用程序框架,包括一个主窗口和一些基本的 UI 元素,如按钮和文本框。
import wx
import os
import xml.etree.ElementTree as ET
import datetime
class MyApp(wx.App):
def OnInit(self):
self.frame = MyFrame(None, title="HTML File Generator")
self.frame.Show()
return True
class MyFrame(wx.Frame):
def __init__(self, parent, title):
super().__init__(parent, title=title, size=(600, 400))
panel = wx.Panel(self)
vbox = wx.BoxSizer(wx.VERTICAL)
# Path selection
hbox1 = wx.BoxSizer(wx.HORIZONTAL)
self.path_txt = wx.TextCtrl(panel)
path_btn = wx.Button(panel, label="选择")
path_btn.Bind(wx.EVT_BUTTON, self.on_select_path)
hbox1.Add(self.path_txt, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
hbox1.Add(path_btn, flag=wx.EXPAND|wx.ALL, border=5)
# Folder name input
hbox2 = wx.BoxSizer(wx.HORIZONTAL)
self.folder_txt = wx.TextCtrl(panel, style=wx.TE_CENTER)
create_folder_btn = wx.Button(panel, label="创建")
create_folder_btn.Bind(wx.EVT_BUTTON, self.on_create_folder)
hbox2.Add(self.folder_txt, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
hbox2.Add(create_folder_btn, flag=wx.EXPAND|wx.ALL, border=5)
# HTML code input
hbox3 = wx.BoxSizer(wx.HORIZONTAL)
self.html_txt = wx.TextCtrl(panel, style=wx.TE_MULTILINE)
hbox3.Add(self.html_txt, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
# HTML file name input
hbox4 = wx.BoxSizer(wx.HORIZONTAL)
self.html_filename_txt = wx.TextCtrl(panel, style=wx.TE_CENTER)
save_html_btn = wx.Button(panel, label="保存")
save_html_btn.Bind(wx.EVT_BUTTON, self.on_save_html)
hbox4.Add(self.html_filename_txt, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
hbox4.Add(save_html_btn, flag=wx.EXPAND|wx.ALL, border=5)
# Batch record selection
hbox5 = wx.BoxSizer(wx.HORIZONTAL)
self.batch_choice = wx.Choice(panel)
load_batch_btn = wx.Button(panel, label="加载记录")
load_batch_btn.Bind(wx.EVT_BUTTON, self.on_load_batch)
hbox5.Add(self.batch_choice, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
hbox5.Add(load_batch_btn, flag=wx.EXPAND|wx.ALL, border=5)
# Save settings button
hbox6 = wx.BoxSizer(wx.HORIZONTAL)
save_settings_btn = wx.Button(panel, label="保存设置")
save_settings_btn.Bind(wx.EVT_BUTTON, self.on_save_settings)
hbox6.Add(save_settings_btn, flag=wx.EXPAND|wx.ALL, border=5)
vbox.Add(hbox1, flag=wx.EXPAND)
vbox.Add(hbox2, flag=wx.EXPAND)
vbox.Add(hbox3, proportion=1, flag=wx.EXPAND)
vbox.Add(hbox4, flag=wx.EXPAND)
vbox.Add(hbox5, flag=wx.EXPAND)
vbox.Add(hbox6, flag=wx.EXPAND)
panel.SetSizer(vbox)
self.Bind(wx.EVT_SHOW, self.on_show)
def on_select_path(self, event):
with wx.DirDialog(self, "选择保存路径", style=wx.DD_DEFAULT_STYLE) as dialog:
if dialog.ShowModal() == wx.ID_OK:
self.path_txt.SetValue(dialog.GetPath())
def on_create_folder(self, event):
path = self.path_txt.GetValue()
folder_name = self.folder_txt.GetValue()
if path and folder_name:
full_path = os.path.join(path, folder_name)
os.makedirs(full_path, exist_ok=True)
wx.MessageBox(f"文件夹 {folder_name} 创建成功", "提示", wx.OK | wx.ICON_INFORMATION)
else:
wx.MessageBox("请先选择保存路径并输入文件夹名称", "错误", wx.OK | wx.ICON_ERROR)
def on_save_html(self, event):
path = self.path_txt.GetValue()
folder_name = self.folder_txt.GetValue()
html_code = self.html_txt.GetValue()
html_filename = self.html_filename_txt.GetValue() + ".html"
if path and folder_name and html_code and html_filename:
full_path = os.path.join(path, folder_name, html_filename)
with open(full_path, "w", encoding="utf-8") as file:
file.write(html_code)
wx.MessageBox(f"HTML 文件 {html_filename} 保存成功", "提示", wx.OK | wx.ICON_INFORMATION)
else:
wx.MessageBox("请确保所有输入框都已填满", "错误", wx.OK | wx.ICON_ERROR)
def on_load_batch(self, event):
batch_name = self.batch_choice.GetStringSelection()
if batch_name:
tree = ET.parse('settings.xml')
root = tree.getroot()
batch = root.find(f"batch[@name='{batch_name}']")
if batch is not None:
self.path_txt.SetValue(batch.find('path').text)
self.folder_txt.SetValue(batch.find('folder').text)
self.html_txt.SetValue(batch.find('html').text)
self.html_filename_txt.SetValue(batch.find('filename').text)
def on_save_settings(self, event):
self.save_settings()
def save_settings(self):
path = self.path_txt.GetValue()
folder_name = self.folder_txt.GetValue()
html_code = self.html_txt.GetValue()
html_filename = self.html_filename_txt.GetValue()
batch_name = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
if os.path.exists("settings.xml"):
tree = ET.parse("settings.xml")
root = tree.getroot()
else:
root = ET.Element("settings")
batch = ET.SubElement(root, "batch", name=batch_name)
ET.SubElement(batch, "path").text = path
ET.SubElement(batch, "folder").text = folder_name
ET.SubElement(batch, "html").text = html_code
ET.SubElement(batch, "filename").text = html_filename
tree = ET.ElementTree(root)
tree.write("settings.xml", encoding="utf-8", xml_declaration=True)
wx.MessageBox("设置已保存", "提示", wx.OK | wx.ICON_INFORMATION)
self.update_batch_choice()
def update_batch_choice(self):
if os.path.exists("settings.xml"):
tree = ET.parse("settings.xml")
root = tree.getroot()
batch_names = [batch.attrib['name'] for batch in root.findall('batch')]
self.batch_choice.Clear()
self.batch_choice.AppendItems(batch_names)
def on_show(self, event):
self.update_batch_choice()
if __name__ == "__main__":
app = MyApp()
app.MainLoop()
3. 代码说明
- 初始化应用程序和主窗口:创建 wxPython 应用程序和主窗口,其中包括所有 UI 元素。
- 选择保存路径:使用
wx.DirDialog
来选择保存路径,并将路径显示在文本框中。 - 创建文件夹:根据用户输入的文件夹名称,在选定路径下创建新文件夹。
- 保存 HTML 文件:根据用户输入的 HTML 代码和文件名,将 HTML 文件保存在选定路径和文件夹下。
- 保存设置:在保存设置按钮点击事件中,将当前配置保存到
settings.xml
文件中。 - 加载批次:从
settings.xml
文件中加载保存的配置,并更新下拉框中的选项。 - 显示时更新批次选项:在窗口显示时,调用
update_batch_choice
方法,确保下拉框中的选项是最新的。
4. 运行应用程序
保存上述代码到一个 Python 文件中,然后运行该文件。你将看到一个带有多个输入框和按钮的 GUI 应用程序。你可以选择保存路径、创建文件夹、输入 HTML 代码并保存为 HTML 文件。此外,你可以保存当前设置并在下次启动应用程序时加载之前的配置。