はじめに:
この記事では、wxPython ライブラリを使用してキャプションおよび URL マネージャー アプリケーションを作成する方法について説明します。このアプリケーションには、ユーザーがキャプションと URL を入力して XML ファイルに保存できるグラフィカル ユーザー インターフェイスがあります。さらに、フォルダーを参照して HTML ファイルを選択する機能が提供され、別の Python スクリプトを実行できます。
C:\pythoncode\blog\savexml.py
ソフトウェア開発では、強力で使いやすいユーザー インターフェイスを作成することが最も重要です。wxPython ライブラリは、Python 開発者にクロスプラットフォームのグラフィカル ユーザー インターフェイスを作成する簡単かつ強力な方法を提供します。この記事では、wxPython ライブラリを使用してキャプションおよび URL マネージャー アプリケーションを作成する方法を紹介します。見てみましょう。
まず、wxPython ライブラリをインストールする必要があります。pip コマンドを使用してインストールできます。
pip install wxPython
インストールが完了したら、コードの記述を開始できます。完全なコードは次のとおりです。
import wx
import os
import xml.etree.ElementTree as ET
import subprocess
class MyFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, title="Caption and URL Manager", size=(800, 600))
self.panel = wx.Panel(self)
# 创建Caption和URL输入框
self.caption_label = wx.StaticText(self.panel, label="Caption:")
self.caption_text = wx.TextCtrl(self.panel)
self.url_label = wx.StaticText(self.panel, label="URL:")
self.url_text = wx.TextCtrl(self.panel)
# 创建按钮并绑定事件处理函数
self.save_button = wx.Button(self.panel, label="Save")
self.save_button.Bind(wx.EVT_BUTTON, self.on_save_button_click)
self.run_button = wx.Button(self.panel, label="Run createbuttonfromxml.py")
self.run_button.Bind(wx.EVT_BUTTON, self.on_run_button_click)
# 创建Memo文本框用于显示data.xml内容
self.memo = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE|wx.TE_READONLY)
# 创建文件夹浏览按钮
self.browse_button = wx.Button(self.panel, label="Browse Folder")
self.browse_button.Bind(wx.EVT_BUTTON, self.on_browse_button_click)
# 创建文件列表框
self.file_listbox = wx.ListBox(self.panel)
self.file_listbox.Bind(wx.EVT_LISTBOX, self.on_file_listbox_select)
# 创建水平和垂直尺寸器布局
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.caption_label, 0, wx.ALL, 5)
sizer.Add(self.caption_text, 0, wx.EXPAND|wx.ALL, 5)
sizer.Add(self.url_label, 0, wx.ALL, 5)
sizer.Add(self.url_text, 0, wx.EXPAND|wx.ALL, 5)
sizer.Add(self.save_button, 0, wx.ALL, 5)
sizer.Add(self.run_button, 0, wx.ALL, 5)
sizer.Add(self.memo, 1, wx.EXPAND|wx.ALL, 5)
sizer.Add(self.browse_button, 0, wx.ALL, 5)
sizer.Add(self.file_listbox, 1, wx.EXPAND|wx.ALL, 5)
self.panel.SetSizer(sizer)
self.Show()
def on_save_button_click(self, event):
caption = self.caption_text.GetValue()
url = self.url_text.GetValue()
tree = ET.ElementTree()
try:
tree.parse('data.xml')
root = tree.getroot()
except FileNotFoundError:
root = ET.Element("data")
tree._setroot(root)
new_item = ET.SubElement(root, "item")
ET.SubElement(new_item, "caption").text = caption
ET.SubElement(new_item, "url").text = url
tree.write('data.xml')
self.update_memo_content()
def on_run_button_click(self, event):
try:
subprocess.run(["python", "createformbuttonfromxml.py"], check=True)
except subprocess.CalledProcessError as e:
wx.MessageBox(f"Error running createformbuttonfromxml.py: {
e}", "Error", wx.OK|wx.ICON_ERROR)
def on_browse_button_click(self, event):
dlg = wx.DirDialog(self.panel, "Choose a folder", style=wx.DD_DEFAULT_STYLE)
if dlg.ShowModal() == wx.ID_OK:
folder_path = dlg用户选择的文件夹路径
files = os.listdir(folder_path)
self.file_listbox.Clear()
self.file_listbox.InsertItems(files, 0)
dlg.Destroy()
def on_file_listbox_select(self, event):
selection = self.file_listbox.GetStringSelection()
self.update_memo_content(selection)
def update_memo_content(self, selection=None):
if selection:
file_path = os.path.join(folder_path, selection)
with open(file_path, "r") as file:
content = file.read()
else:
content = ""
self.memo.SetValue(content)
app = wx.App()
frame = MyFrame(None)
app.MainLoop()
上記は、単純なキャプションおよび URL マネージャー アプリケーションのコード サンプルです。このアプリケーションでは、wxPython ライブラリを使用してメイン ウィンドウを作成し、キャプションと URL の入力ボックス、保存ボタン、実行ボタン、メモ テキスト ボックス、フォルダー参照ボタン、ファイル リスト ボックスなどのコントロールをウィンドウに追加します。ユーザーはキャプションと URL を入力し、保存ボタンをクリックして XML ファイルに保存できます。ユーザーは、フォルダーを参照して HTML ファイルを選択し、ファイルの内容を [メモ] テキスト ボックスに表示することもできます。「実行」ボタンをクリックすると、別の Python スクリプトが実行されます。
これは、ニーズに合わせて拡張およびカスタマイズできる単純なサンプル アプリケーションです。wxPython ライブラリを使用すると、さまざまなタイプのグラフィカル ユーザー インターフェイス アプリケーションを簡単に作成し、ユーザーにフレンドリーなインタラクティブなエクスペリエンスを提供できます。
完全なコード:
import wx
import os
import xml.etree.ElementTree as ET
import subprocess
class MyFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, title="Caption and URL Manager", size=(800, 600))
self.panel = wx.Panel(self)
# 创建Caption和URL输入框
self.caption_label = wx.StaticText(self.panel, label="Caption:")
self.caption_text = wx.TextCtrl(self.panel)
self.url_label = wx.StaticText(self.panel, label="URL:")
self.url_text = wx.TextCtrl(self.panel)
# 创建按钮并绑定事件处理函数
self.save_button = wx.Button(self.panel, label="Save")
self.save_button.Bind(wx.EVT_BUTTON, self.on_save_button_click)
self.run_button = wx.Button(self.panel, label="Run createbuttonfromxml.py")
self.run_button.Bind(wx.EVT_BUTTON, self.on_run_button_click)
# 创建Memo文本框用于显示data.xml内容
self.memo = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE | wx.TE_READONLY)
# 创建文件夹浏览按钮
self.browse_button = wx.Button(self.panel, label="Browse Folder")
self.browse_button.Bind(wx.EVT_BUTTON, self.on_browse_button_click)
# 创建文件列表框
# self.file_listbox = wx.ListBox(self.panel)
# 创建文件列表框
self.file_listbox = wx.ListBox(self.panel)
self.file_listbox.Bind(wx.EVT_LISTBOX, self.on_file_listbox_select)
# 创建水平和垂直尺寸器布局
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.caption_label, 0, wx.ALL, 5)
sizer.Add(self.caption_text, 0, wx.EXPAND | wx.ALL, 5)
sizer.Add(self.url_label, 0, wx.ALL, 5)
sizer.Add(self.url_text, 0, wx.EXPAND | wx.ALL, 5)
sizer.Add(self.save_button, 0, wx.ALL, 5)
sizer.Add(self.run_button, 0, wx.ALL, 5)
sizer.Add(self.memo, 1, wx.EXPAND | wx.ALL, 5)
sizer.Add(self.browse_button, 0, wx.ALL, 5)
sizer.Add(self.file_listbox, 1, wx.EXPAND | wx.ALL, 5)
self.panel.SetSizer(sizer)
self.Show()
def on_save_button_click(self, event):
caption = self.caption_text.GetValue()
url = self.url_text.GetValue()
tree = ET.ElementTree()
try:
tree.parse('data.xml')
root = tree.getroot()
except FileNotFoundError:
root = ET.Element("data")
tree._setroot(root)
new_item = ET.SubElement(root, "item")
ET.SubElement(new_item, "caption").text = caption
ET.SubElement(new_item, "url").text = url
tree.write('data.xml')
self.update_memo_content()
# def on_run_button_click(self, event):
# os.system("python createbuttonfromxml.py")
def on_run_button_click(self, event):
try:
subprocess.run(["python", "createformbuttonfromxml.py"], check=True)
except subprocess.CalledProcessError as e:
wx.MessageBox(f"Error running createformbuttonfromxml.py: {
e}", "Error", wx.OK | wx.ICON_ERROR)
def on_browse_button_click(self, event):
dlg = wx.DirDialog(self.panel, "Choose a folder", style=wx.DD_DEFAULT_STYLE)
if dlg.ShowModal() == wx.ID_OK:
folder_path = dlg.GetPath()
self.update_file_listbox(folder_path)
dlg.Destroy()
def update_memo_content(self):
try:
with open('data.xml', 'r') as f:
self.memo.SetValue(f.read())
except FileNotFoundError:
self.memo.SetValue("data.xml file not found.")
def update_file_listbox(self, folder_path):
self.file_listbox.Clear()
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith(".html"):
file_path = os.path.join(root, file)
self.file_listbox.Append(file_path)
def update_url_text(self, event):
selected_file = self.file_listbox.GetStringSelection()
self.url_text.SetValue(selected_file)
def on_file_listbox_select(self, event):
selected_file = self.file_listbox.GetStringSelection()
self.url_text.SetValue(selected_file)
app = wx.App()
frame = MyFrame(None)
app.MainLoop()
概要:
この記事では、wxPython ライブラリを使用してキャプションおよび URL マネージャー アプリケーションを作成する方法について説明します。このサンプル アプリケーションを通じて、グラフィカル ユーザー インターフェイスの作成、ユーザー入力の処理、XML ファイルへのデータの保存、フォルダーの参照、ファイルの選択、その他の Python スクリプトの実行方法を学ぶことができます。この記事が wxPython ライブラリの使用を開始するのに役立ち、より強力な GUI アプリケーションを開発するきっかけになれば幸いです。