Use xml in python to quickly create Caption and URL bookmark manager applications

Introduction:
This article describes how to use the wxPython library to create a Caption and URL manager application. The application has a graphical user interface that allows the user to enter a Caption and URL, and saves it to an XML file. Additionally, the ability to browse folders and select HTML files is provided, and another Python script can be run.
C:\pythoncode\blog\savexml.py
insert image description here

In software development, creating powerful and easy-to-use user interfaces is of paramount importance. The wxPython library provides Python developers with an easy and powerful way to create cross-platform graphical user interfaces. This article will introduce how to use the wxPython library to create a Caption and URL manager application, let's take a look!

First, we need to install the wxPython library. You can use the pip command to install:

pip install wxPython

After the installation is complete, we can start writing code. Here is the complete code:

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()

Above is a code sample for a simple Caption and URL manager application. In this application, we use the wxPython library to create a main window, and add controls such as Caption and URL input boxes, save buttons, run buttons, Memo text boxes, folder browse buttons, and file list boxes to the window. Users can enter Caption and URL, and click the save button to save it to an XML file. Users can also browse folders and select HTML files to display the contents of the file in the Memo text box. Clicking the Run button executes another Python script.

This is just a simple sample application that you can extend and customize to your needs. Using the wxPython library, you can easily create various types of graphical user interface applications and provide users with a friendly interactive experience.
Full code:

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()

Summary:
This article describes how to create a Caption and URL manager application using the wxPython library. Through this sample application, you can learn how to create a graphical user interface, handle user input, save data to an XML file, browse folders, select files, and run other Python scripts. Hope this article can help you get started with the wxPython library and inspire you to develop more powerful GUI applications!

Guess you like

Origin blog.csdn.net/winniezhang/article/details/132324670