【python】wxpython的界面实例

需要先安装依赖

pip install wxPython

界面代码:

# coding=utf-8
import configparser
import os
import sys
import re
import time
import threading

import wx


class MyApp(wx.Frame):
    def __init__(self, window, properties):
        wx.Frame.__init__(
            self, window, id=wx.ID_ANY,
            title=properties.get("title"),
            pos=wx.DefaultPosition,
            size=wx.Size(properties.get("size")),
            style=wx.DEFAULT_FRAME_STYLE ^ wx.MAXIMIZE_BOX
        )
        self.ini = os.path.join(os.environ["appdata"], 'my_app.ini')
        self.configuration = None
        self.support_product = ["A", "B", "C", "D", "E", "F", "G", "H","I", "J"]
        self.support_version_map = {
            "A": ["AA", "AB"],
            "B": ["BB", "BCD", "BFD"],
            "C": ["CL"],
            "D": ["DD"],
            "E": ["EE", "EA"],
            "F": ["FF", "FE", "FG", "FFF", "F1"],
            "G": ["GG"],
            "H": ["HZ", "HP"],
            "I": ["I"],
            "J": ["JJ", "JP"],
        }
        self.dst_version = ["ABC", "10JK", "JQK", "10JQKA"]
        self.help_info = "使用说明:\n1、read me\n"
        self.SetSizeHints(wx.DefaultSize, wx.DefaultSize)
        self.SetExtraStyle(wx.FRAME_EX_METAL)
        self.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_MENU))
        table = wx.GridBagSizer(0, 0)
        table.SetFlexibleDirection(wx.BOTH)
        table.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
        label_file = wx.StaticText(self, wx.ID_ANY, '文件路径', wx.DefaultPosition, wx.DefaultSize, wx.ALIGN_RIGHT)
        label_file.Wrap(-1)
        label_file.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False, '微软雅黑'))
        table.Add(label_file, wx.GBPosition(1, 1), wx.GBSpan(1, 1), wx.ALL, 5)
        self.file = wx.FilePickerCtrl(self, wx.ID_ANY, wx.EmptyString, '选择文件', '*.*', wx.DefaultPosition,
                                      wx.Size(550, -1), wx.FLP_DEFAULT_STYLE)
        self.file.SetFont(wx.Font(11, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False, '微软雅黑'))
        table.Add(self.file, wx.GBPosition(1, 2), wx.GBSpan(1, 5), wx.ALL, 5)
        self.run_button = wx.Button(self, wx.ID_ANY, '运行', wx.DefaultPosition, wx.Size(120, -1), wx.NO_BORDER)
        self.run_button.SetFont(wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False, '微软雅黑'))
        self.run_button.SetForegroundColour("#ffffff")
        self.run_button.SetBackgroundColour("#2fa4e7")
        table.Add(self.run_button, wx.GBPosition(1, 7), wx.GBSpan(1, 1), wx.ALL, 5)
        label_src_product = wx.StaticText(self, wx.ID_ANY, '选择A', wx.DefaultPosition, wx.DefaultSize,
                                          wx.ALIGN_RIGHT)
        label_src_product.Wrap(-1)
        label_src_product.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False, '微软雅黑'))
        table.Add(label_src_product, wx.GBPosition(2, 1), wx.GBSpan(1, 1), wx.ALL, 5)
        choice_src_product = self.get_src_product_list()
        self.choice_src_product = wx.Choice(self, wx.ID_ANY, wx.DefaultPosition, wx.Size(135, -1), choice_src_product,
                                            0)
        self.choice_src_product.SetSelection(0)
        table.Add(self.choice_src_product, wx.GBPosition(2, 2), wx.GBSpan(1, 1), wx.ALL, 5)
        label_src_version = wx.StaticText(self, wx.ID_ANY, 'A联动选择', wx.DefaultPosition, wx.DefaultSize, wx.ALIGN_RIGHT)
        label_src_version.Wrap(-1)
        label_src_version.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False, '微软雅黑'))
        table.Add(label_src_version, wx.GBPosition(2, 3), wx.GBSpan(1, 1), wx.ALL, 5)
        choice_src_version = self.get_src_version_list()
        self.choice_src_version = wx.Choice(self, wx.ID_ANY, wx.DefaultPosition, wx.Size(135, -1), choice_src_version,
                                            0)
        self.choice_src_version.SetSelection(0)
        table.Add(self.choice_src_version, wx.GBPosition(2, 4), wx.GBSpan(1, 1), wx.ALL, 5)
        label_dst_version = wx.StaticText(self, wx.ID_ANY, '选择B', wx.DefaultPosition, wx.Size(-1, 30), wx.ALIGN_CENTRE)
        label_dst_version.Wrap(-1)
        label_dst_version.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False, '微软雅黑'))
        table.Add(label_dst_version, wx.GBPosition(2, 5), wx.GBSpan(1, 1), wx.ALL, 5)
        self.choice_dst_version = wx.Choice(self, wx.ID_ANY, wx.DefaultPosition, wx.Size(135, -1), self.dst_version, 0)
        self.choice_dst_version.SetSelection(0)
        table.Add(self.choice_dst_version, wx.GBPosition(2, 6), wx.GBSpan(1, 1), wx.ALL, 5)
        clean_log = wx.Button(self, wx.ID_ANY, '清空日志', wx.DefaultPosition, wx.Size(120, -1), wx.NO_BORDER)
        clean_log.SetFont(wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False, '微软雅黑'))
        clean_log.SetForegroundColour("#ffffff")
        clean_log.SetBackgroundColour("#2fa4e7")
        table.Add(clean_log, wx.GBPosition(2, 7), wx.GBSpan(1, 1), wx.ALL, 5)
        self.log = wx.TextCtrl(self, wx.ID_ANY, self.help_info, wx.DefaultPosition, wx.Size(750, 400), wx.TE_MULTILINE)
        self.log.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False, '宋体'))
        table.Add(self.log, wx.GBPosition(3, 1), wx.GBSpan(1, 9), wx.ALL, 5)
        self.gauge_bar = wx.Gauge(self, wx.ID_ANY, 0, wx.DefaultPosition, wx.Size(750, -1), wx.GA_HORIZONTAL)
        table.Add(self.gauge_bar, wx.GBPosition(4, 1), wx.GBSpan(1, 9), wx.ALL, 5)
        self.SetSizer(table)
        self.Layout()
        self.Centre(wx.BOTH)
        self.choice_src_product.Bind(wx.EVT_CHOICE, self.change_select_source_product)
        self.choice_src_version.Bind(wx.EVT_CHOICE, self.change_help_info)
        self.run_button.Bind(wx.EVT_BUTTON, self.main)
        clean_log.Bind(wx.EVT_BUTTON, self.clean_log_textarea)
        self.load_config()

    def load_config(self):
        if not os.path.exists(self.ini):
            return
        try:
            config = configparser.ConfigParser()
            config.read(self.ini, encoding="utf-8")
            self.file.SetPath(config.get("file", "path"))
            self.choice_src_product.SetSelection(config.getint("select", "src_product"))
            self.change_select_source_product("")
            self.choice_src_version.SetSelection(config.getint("select", "src_version"))
            self.choice_dst_version.SetSelection(config.getint("select", "dst_version"))
            self.change_help_info("")
        except Exception as e:
            print("[Error] load_config {}".format(e))

    def save_config(self):
        config = configparser.ConfigParser()
        config.add_section("file")
        config.set("file", "path", self.file.GetPath())
        config.add_section("select")
        config.set("select", "src_product", str(self.choice_src_product.GetCurrentSelection()))
        config.set("select", "src_version", str(self.choice_src_version.GetCurrentSelection()))
        config.set("select", "dst_version", str(self.choice_dst_version.GetCurrentSelection()))
        config.write(open(self.ini, "w", encoding="utf-8"))

    def clean_log_textarea(self, _):
        self.log.Clear()
        self.log.AppendText(self.help_info)
        self.gauge_bar.SetValue(0)

    def write_program_2_log_textarea(self, info):
        self.log.AppendText("="*40+info+"="*40+"\n")

    def write_2_log_textarea(self, info):
        timestamp = time.strftime('%H:%M:%S', time.localtime(time.time()))
        self.log.AppendText("[{}]{}\n".format(timestamp, info))

    def change_select_source_product(self, _):
        product = self.choice_src_product.GetString(self.choice_src_product.GetSelection())
        version = self.support_version_map.get(product, [])
        self.choice_src_version.SetItems(version)
        if version:
            self.choice_dst_version.SetSelection(0)

    def get_src_product_list(self):
        return self.support_product

    def get_src_version_list(self):
        product = self.choice_src_product.GetString(self.choice_src_product.GetSelection())
        return self.support_version_map.get(product, [])

    def change_help_info(self, _):
        version = self.choice_src_version.GetString(self.choice_src_version.GetSelection())
        help_info = "{}的使用说明".format(version)
        self.log.Clear()
        self.log.AppendText(help_info)

    def main(self, _):
        self.run_button.Enable(False)
        self.save_config()
        t = threading.Thread(target=self.back_job, args=())
        t.start()

    def back_job(self):
        self.log.Clear()
        self.gauge_bar.SetValue(0)
        self.gauge_bar.SetRange(1)
        self.write_program_2_log_textarea("操作开始")
        self.configuration = self.file.GetPath().strip()
        self.write_2_log_textarea("file: {}".format(self.configuration))
        product = self.choice_src_product.GetString(self.choice_src_product.GetSelection())
        version = self.choice_src_version.GetString(self.choice_src_version.GetSelection())
        self.write_2_log_textarea("source product: {} source version: {}".format(product, version))
        self.run_button.Enable(True)
        self.gauge_bar.SetValue(1)
        self.write_program_2_log_textarea("操作结束")

def app_gui_show(version):
    app_name = "小工具"
    app = wx.App()
    filename = sys.argv[0]
    ma = re.search(r"(v[\d.]+)\.exe", filename)
    if ma:
        version = ma.group(1)
    properties = {"title": "{} {}".format(app_name, version), "size": (800, 600)}
    window = MyApp(None, properties)
    # tmp = open("tmp.ico", "wb+")
    # tmp.write(base64.b64decode(logo.ico))
    # tmp.close()
    # icon = wx.Icon(name="tmp.ico", type=wx.BITMAP_TYPE_ICO)
    # window.SetIcon(icon)
    window.Show(True)
    # os.remove("tmp.ico")
    app.MainLoop()


app_gui_show("v1.0")

界面效果:

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在Python中,可以使用Tkinter模块创建GUI应用程序界面。在Tkinter中,可以使用类来创建窗口和其他GUI控件。以下是一个简单的示例: ```python import tkinter as tk class App(tk.Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.pack() self.create_widgets() def create_widgets(self): self.hi_there = tk.Button(self) self.hi_there["text"] = "Hello World\n(click me)" self.hi_there["command"] = self.say_hi self.hi_there.pack(side="top") self.quit = tk.Button(self, text="QUIT", fg="red", command=self.master.destroy) self.quit.pack(side="bottom") def say_hi(self): print("hi there, everyone!") root = tk.Tk() app = App(master=root) app.mainloop() ``` 在此示例中,我们创建了一个名为`App`的类,该类继承自`tk.Frame`。在`__init__`方法中,我们初始化`App`实例,并创建了一些GUI控件。`create_widgets`方法用于创建这些控件,并将它们放置在窗口中。 在`say_hi`方法中,我们定义了一个简单的命令,当用户单击“Hello World”按钮时会调用该方法。当用户单击“QUIT”按钮时,我们调用`self.master.destroy`方法来关闭应用程序窗口。 最后,在主程序中,我们创建了一个`Tk`实例,并将其传递给`App`类的构造函数。我们通过调用`mainloop`方法来启动主事件循环,该事件循环负责处理用户输入和其他GUI事件。 ### 回答2: Python的程序界面可以通过使用类(class)来实现。在Python中,类是一种面向对象的编程概念,可以用来创建对象和定义对象的属性和方法。 一个简单的Python程序界面类的例子如下: ```python import tkinter as tk class ProgramInterface: def __init__(self, root): self.root = root self.button = tk.Button(root, text="Click me", command=self.button_clicked) self.button.pack() def button_clicked(self): print("Button clicked!") # 创建根窗口 root = tk.Tk() # 创建程序界面对象 interface = ProgramInterface(root) # 进入事件循环 root.mainloop() ``` 在上面的例子中,我们首先导入了`tkinter`模块,这是Python标准库中用于创建GUI程序的模块。然后定义了一个名为`ProgramInterface`的类,该类具有一个构造函数`__init__`,用于创建程序界面的各个组件。在这个例子中,我们创建了一个按钮,当点击按钮时,会调用`button_clicked`方法,并输出"Button clicked!"。 然后我们创建了根窗口对象`root`,并将其传递给`ProgramInterface`类的构造函数来创建程序界面对象`interface`。最后,通过调用`mainloop`方法启动事件循环,使程序进入可响应用户操作的状态。 通过使用类来创建Python程序界面,我们可以更好地组织和管理界面的各个组件和功能。使用类的优点在于可以通过创建多个相似的对象来实现可复用的界面,并可以利用类的继承功能实现更复杂界面设计。 ### 回答3: Python程序界面类是用来创建和管理程序用户界面的类。它可以包含各种图形用户界面(GUI)元素,例如窗口、按钮、文本框、标签等,以及相应的事件处理和功能实现。 Python中常用的实现程序界面的类库有Tkinter、PyQt、wxPython等。其中,Tkinter是Python自带的标准GUI库,使用简单、易学,适合初学者。而PyQt和wxPython是基于著名的GUI库Qt和wxWidgets进行封装的,提供了更强大和灵活的特性。 在创建Python程序界面类时,需要定义类的属性和方法。属性可以包括窗口大小、标题、布局方式等,方法可以包括按钮点击事件、菜单选择事件等。通过使用类的属性和方法,可以创建自定义的用户界面,并实现所需的功能。 一个简单的例子是使用Tkinter库创建一个窗口界面的类: ```python import tkinter as tk class MyGUI: def __init__(self, master): self.master = master self.master.title("My GUI") self.master.geometry("300x200") self.btn = tk.Button(self.master, text="Click Me", command=self.button_click) self.btn.pack() def button_click(self): print("Button clicked!") if __name__ == "__main__": root = tk.Tk() gui = MyGUI(root) root.mainloop() ``` 在这个例子中,首先导入了Tkinter库,并创建了一个名为`MyGUI`的类,该类包含了一个初始化方法`__init__`,用来初始化窗口属性和创建按钮等界面元素。`button_click`方法用来处理按钮点击事件。最后,在主程序中创建了一个Tkinter的根窗口,并将该窗口传给`MyGUI`类的实例,通过调用`mainloop`方法使程序进入事件循环。 通过定义类的属性和方法,可以根据实际需求创建复杂的、功能丰富的Python程序界面类。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值