`
sillycat
  • 浏览: 2526271 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

wxpython入门(九)HTML和其他应用

阅读更多
wxpython入门(九)HTML和其他应用

参考书籍
http://wiki.woodpecker.org.cn/moin/WxPythonInAction

第十六章 应用中的HTML

显示HTML
example:

import wx.html

class MyHtmlFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self,parent,-1,title)
        html = wx.html.HtmlWindow(self)
        if "gtk2" in wx.PlatformInfo:
            html.SetStandardFonts()
        html.SetPage(
            "Here is some  <b>formatted</b>   <i><u>text</u></i>"
            "loaded from a  <font color=\"red\"> string </font>.")

app = wx.PySimpleApp()
frm = MyHtmlFrame(None, "Simple HTML")
frm.Show()
app.MainLoop()

从一个WEB页装载HTML,examples:

import wx
import wx.html

class MyHtmlFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, -1, title, size=(600,400))
        html = wx.html.HtmlWindow(self)
        if "gtk2" in wx.PlatformInfo:
            html.SetStandardFonts()
        wx.CallAfter(html.LoadPage,"http://www.wxpython.org")
app = wx.PySimpleApp()
frm = MyHtmlFrame(None, "Simple HTML Browser")
frm.Show()
app.MainLoop()

带有状态栏和标题栏的HTML窗口,examples:

import wx
import wx.html

class MyHtmlFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, -1, title, size=(600,400))
        self.CreateStatusBar()
        html = wx.html.HtmlWindow(self)
        if "gtk2" in wx.PlatformInfo:
            html.SetStandardFonts()
        html.SetRelatedFrame(self,self.GetTitle() + " -- %s")
        #关联HTML到框架
        html.SetRelatedStatusBar(0) #关联HTML到状态栏
        wx.CallAfter(html.LoadPage, "http://www.wxpython.org")

app = wx.PySimpleApp()
frm = MyHtmlFrame(None, "Simple HTML Browser")
frm.Show()
app.MainLoop()

如何增加对新标记的支持(略)

第十七章 wxPython的打印构架

(略)

第十八章 其它应用

剪贴板应用

examples:

import wx

t1_text = "test1"
t2_text = "test2"
class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self,None,title="Clipboard",size=(500,300))
        p = wx.Panel(self)
        # create the controls
        self.t1 = wx.TextCtrl(p,-1,t1_text,style=wx.TE_MULTILINE|wx.HSCROLL)
        self.t2 = wx.TextCtrl(p,-1,t2_text,style=wx.TE_MULTILINE|wx.HSCROLL)
        copy = wx.Button(p, -1, "Copy")
        paste = wx.Button(p, -1, "Paste")
        # setup the layout with sizers
        fgs = wx.FlexGridSizer(2, 2, 5, 5)
        fgs.AddGrowableRow(0)
        fgs.AddGrowableCol(0)
        fgs.AddGrowableCol(1)
        fgs.Add(self.t1, 0, wx.EXPAND)
        fgs.Add(self.t2, 0, wx.EXPAND)
        fgs.Add(copy, 0, wx.EXPAND)
        fgs.Add(paste, 0, wx.EXPAND)
        border = wx.BoxSizer()
        border.Add(fgs, 1, wx.EXPAND|wx.ALL, 5)
        p.SetSizer(border)
        # Bind events
        self.Bind(wx.EVT_BUTTON, self.OnDoCopy, copy)
        self.Bind(wx.EVT_BUTTON, self.OnDoPaste, paste)
    def OnDoCopy(self, evt):
        #Copy按钮的事件处理函数
        data = wx.TextDataObject()
        data.SetText(self.t1.GetValue())
        if wx.TheClipboard.Open():
            wx.TheClipboard.SetData(data)
            #将数据放置到剪贴板上
            wx.TheClipboard.Close()
        else:
            wx.MessageBox("Unable to open the clipboard", "Error")
    def OnDoPaste(self, evt):
        #Paste按钮的事件处理函数
        success = False
        data = wx.TextDataObject()
        if wx.TheClipboard.Open():
            success = wx.TheClipboard.GetData(data)
            #从剪贴板得到数据
            wx.TheClipboard.Close()
        if success:
            self.t2.SetValue(data.GetText())
            #更新文本控件
        else:
            wx.MessageBox(
                "There is no data in the clipboard in the required format",
                "Error")
app = wx.PySimpleApp()
frm = MyFrame()
frm.Show()
app.MainLoop()

简单的一个拖放源,examples:

import wx
class DragController(wx.Control):
    """
    Just a little control to handle dragging the text from a text
    control.We use a separate control so as to not interfere with
    the native drag-select functionality of the native text control.
    """
    def __init__(self, parent, source, size=(25,25)):
        wx.Control.__init__(self,parent,-1,size=size,style=wx.SIMPLE_BORDER)
        self.source = source
        self.SetMinSize(size)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
    def OnPaint(self, evt):
        # draw a simple arrow
        dc = wx.BufferedPaintDC(self)
        dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
        dc.Clear()
        w, h = dc.GetSize()
        y = h/2
        dc.SetPen(wx.Pen("dark blue", 2))
        dc.DrawLine(w/8,   y,  w-w/8, y)
        dc.DrawLine(w-w/8, y,  w/2,   h/4)
        dc.DrawLine(w-w/8, y,  w/2,   3*h/4)
    def OnLeftDown(self, evt):
        text = self.source.GetValue()
        data = wx.TextDataObject(text)
        dropSource = wx.DropSource(self)#创建释放源
        dropSource.SetData(data)#设置数据
        result = dropSource.DoDragDrop(wx.Drag_AllowMove)#执行释放
        # if the user wants to move the data then we should delete it
        # from the source
        if result == wx.DragMove:
            self.source.SetValue("")#如果需要的话,删除源中的数据
class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title="Drop Source")
        p = wx.Panel(self)
        # create the controls
        label1 = wx.StaticText(p, -1, "Put some text in this control:")
        label2 = wx.StaticText(p, -1,
           "Then drag from the neighboring bitmap and\n"
           "drop in an application that accepts dropped\n"
           "text, such as MS Word.")
        text = wx.TextCtrl(p, -1, "sillycat")
        dragctl = DragController(p, text)
        # setup the layout with sizers
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(label1, 0, wx.ALL, 5)
        hrow = wx.BoxSizer(wx.HORIZONTAL)
        hrow.Add(text, 1, wx.RIGHT, 5)
        hrow.Add(dragctl, 0)
        sizer.Add(hrow, 0, wx.EXPAND|wx.ALL, 5)
        sizer.Add(label2, 0, wx.ALL, 5)
        p.SetSizer(sizer)
        sizer.Fit(self)
app = wx.PySimpleApp()
frm = MyFrame()
frm.Show()
app.MainLoop()

文件拖放到目标的代码示例,examples:

import wx
class MyFileDropTarget(wx.FileDropTarget):
    #声明释放到的目标
    def __init__(self, window):
        wx.FileDropTarget.__init__(self)
        self.window = window
    def OnDropFiles(self, x, y, filenames):#释放文件处理函数数据
        self.window.AppendText("\n%d file(s) dropped at (%d,%d):\n" % (len(filenames),x,y))
        for file in filenames:
            self.window.AppendText("\t%s\n" % file)
class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self,None,title="DropTarget",size=(500,300))
        p = wx.Panel(self)
        # create the controls
        label = wx.StaticText(p,-1,"Drop some files here:")
        text = wx.TextCtrl(p,-1,"",style=wx.TE_MULTILINE|wx.HSCROLL)
        # setup the layout with sizers
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(label, 0, wx.ALL, 5)
        sizer.Add(text, 1, wx.EXPAND|wx.ALL, 5)
        p.SetSizer(sizer)
        # make the text control be a drop target
        dt = MyFileDropTarget(text)#将文本控件作为释放到的目标
        text.SetDropTarget(dt)
app = wx.PySimpleApp()
frm = MyFrame()
frm.Show()
app.MainLoop()

定时器应用
简单的数据时钟,examples:

import wx
import time
class ClockWindow(wx.Window):
    def __init__(self, parent):
        wx.Window.__init__(self, parent)
        self.Bind(wx.EVT_PAINT,self.OnPaint)
        self.timer = wx.Timer(self)
        #创建定时器
        self.Bind(wx.EVT_TIMER,self.OnTimer,self.timer)
        #绑定一个定时器事件
        self.timer.Start(1000)#设定时间间隔
    def Draw(self, dc):
        #绘制当前时间
        t = time.localtime(time.time())
        st = time.strftime("%I:%M:%S", t)
        w, h = self.GetClientSize()
        dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
        dc.Clear()
        dc.SetFont(wx.Font(30, wx.SWISS, wx.NORMAL, wx.NORMAL))
        tw, th = dc.GetTextExtent(st)
        dc.DrawText(st, (w-tw)/2, (h)/2 - th/2)
    def OnTimer(self, evt):
        #显示时间事件处理函数
        dc = wx.BufferedDC(wx.ClientDC(self))
        self.Draw(dc)
    def OnPaint(self, evt):
        dc = wx.BufferedPaintDC(self)
        self.Draw(dc)
class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title="wx.Timer")
        ClockWindow(self)
       

app = wx.PySimpleApp()
frm = MyFrame()
frm.Show()
app.MainLoop()

多线程应用,examples:

import wx
import threading
import random
class WorkerThread(threading.Thread):
    """
    This just simulates some long-running task that periodically sends
    a message to the GUI thread.
    """
    def __init__(self, threadNum, window):
        threading.Thread.__init__(self)
        self.threadNum = threadNum
        self.window = window
        self.timeToQuit = threading.Event()
        self.timeToQuit.clear()
        self.messageCount = random.randint(10,20)
        self.messageDelay = 0.1 + 2.0 * random.random()
    def stop(self):
        self.timeToQuit.set()
    def run(self):#运行一个线程
        msg = "Thread %d iterating %d times with a delay of %1.4f\n" \
              % (self.threadNum, self.messageCount, self.messageDelay)
        wx.CallAfter(self.window.LogMessage, msg)
        for i in range(1, self.messageCount+1):
            self.timeToQuit.wait(self.messageDelay)
            if self.timeToQuit.isSet():
                break
            msg = "Message %d from thread %d\n" % (i, self.threadNum)
            wx.CallAfter(self.window.LogMessage, msg)
        else:#这里不懂,为啥要用else
            wx.CallAfter(self.window.ThreadFinished, self)
        #当循环“自然”终结(循环条件为假)时 else 从句会被执行一次,
        #而当循环是由 break 语句中断时,else从句就不被执行。
class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title="Multi-threaded GUI")
        self.threads = []
        self.count = 0
        panel = wx.Panel(self)
        startBtn = wx.Button(panel, -1, "Start a thread")
        stopBtn  = wx.Button(panel, -1, "Stop all threads")
        self.tc = wx.StaticText(panel, -1, "Worker Threads: 00")
        self.log = wx.TextCtrl(panel,-1,"",style=wx.TE_RICH|wx.TE_MULTILINE)

        inner = wx.BoxSizer(wx.HORIZONTAL)
        inner.Add(startBtn, 0, wx.RIGHT, 15)
        inner.Add(stopBtn, 0, wx.RIGHT, 15)
        inner.Add(self.tc, 0, wx.ALIGN_CENTER_VERTICAL)
        main = wx.BoxSizer(wx.VERTICAL)
        main.Add(inner, 0, wx.ALL, 5)
        main.Add(self.log, 1, wx.EXPAND|wx.ALL, 5)
        panel.SetSizer(main)
        self.Bind(wx.EVT_BUTTON, self.OnStartButton, startBtn)
        self.Bind(wx.EVT_BUTTON, self.OnStopButton, stopBtn)
        self.Bind(wx.EVT_CLOSE,  self.OnCloseWindow)
        self.UpdateCount()
    def OnStartButton(self, evt):
        self.count += 1
        thread = WorkerThread(self.count, self)#创建一个线程
        self.threads.append(thread)
        self.UpdateCount()
        thread.start()#启动线程
    def OnStopButton(self, evt):
        self.StopThreads()
        self.UpdateCount()
    def OnCloseWindow(self, evt):
        self.StopThreads()
        self.Destroy()
    def StopThreads(self):#从池中删除线程
        while self.threads:
            thread = self.threads[0]
            thread.stop()
            self.threads.remove(thread)
    def UpdateCount(self):
        self.tc.SetLabel("Worker Threads: %d" % len(self.threads))
    def LogMessage(self, msg):#注册一个消息
        self.log.AppendText(msg)
    def ThreadFinished(self, thread):#删除线程
        self.threads.remove(thread)
        self.UpdateCount()
app = wx.PySimpleApp()
frm = MyFrame()
frm.Show()
app.MainLoop()

分享到:
评论

相关推荐

    wxPython-入门教程.pdf

    wxPython的出现弥补了这一不足,使得开发者能够用Python编写出快速、易于编写的GUI应用,并且无需修改就能跨平台运行。 【移植性】是wxPython的一大亮点。与Java相比,虽然Java也强调跨平台,但Java虚拟机的大小和...

    活学活用wxPython

    - 探讨了如何设计和规划wxPython应用程序的结构,以便于代码管理和后续开发。 - **第六章:使用wxPython基本构件** - 细致地讲解了wxPython中常见的基本控件,如按钮、文本框等,并提供了示例代码。 #### 三、...

    Python 基础入门教程

    Python是一种高级编程...最后,Python在部署方面也提供了多种工具和框架,如构建Web应用的Flask和Django,以及Web框架中的WSGI接口。此外,Python也支持编写移动应用,可以利用Kivy等框架进行跨平台的移动应用开发。

    ojuice:用Python编写的自托管Todolist应用

    入门 这些说明将为您提供在本地计算机上运行并运行的项目的副本,以进行开发和测试。 有关如何在实时系统上部署项目的注释,请参阅部署。 先决条件 您需要安装软件什么东西以及如何安装它们: Python 2.7 在Windows...

    Python-中国独立开发者项目列表分享大家都在做什么

    6. 桌面应用:PyQt、wxPython和Tkinter等库为Python提供了创建桌面应用的可能。独立开发者可以利用这些工具开发用户界面友好、功能丰富的桌面软件。 7. 云服务与运维:Ansible和SaltStack是Python在基础设施自动化...

    python语言学习说明指导

    7. 图形界面:Tkinter、PyQt、wxPython等库可用于构建图形用户界面,使Python应用更具交互性。 总之,Python语言不仅适用于初学者快速入门编程,也是专业人士解决复杂问题的有效工具。通过深入学习和实践,你可以...

    python 有用资料

    根据给定的文件信息,以下是从“python 有用资料”中提炼出的关键知识点: ...以上知识点涵盖了Python学习和开发的各个方面,从入门到进阶,从Web开发到科学计算,为Python开发者提供了全方位的资源和支持。

    RFS自动化测试培训.pptx

    1. **在线安装**:首先确保安装Python 2.7,接着安装wxPython,然后使用pip安装Robot Framework、RIDE(Robot Framework的图形化界面)、Selenium2Library和对应的浏览器驱动。 2. **离线安装**:如果网络条件有限,...

    Python源码实例-名言查询.zip

    5. **游戏开发**:Python在游戏开发中的应用可能不太直接,但若名言查询是作为游戏的一部分,比如每日名言激励玩家,Python的`pygame`库可以用于创建简单的2D游戏,显示和更新名言。 6. **文件操作**:实例可能包含...

    Python+selenium+robot环境搭建

    - 将 `D:\Python27` 和 `D:\Python27\Scripts` 添加到系统环境变量 `PATH` 中。 - 确保不同环境变量之间使用分号 (`;`) 分隔。 **2. wxPython 安装** - **安装包**: wxPython - **安装方式**: 运行 `wxPython3.0...

    python安装网址

    - **特点**: Pygame 用于开发游戏和其他多媒体应用程序,基于 SDL。 - **PyQt / PySide**: [https://riverbankcomputing.com/software/pyqt/intro](https://riverbankcomputing.com/software/pyqt/intro), ...

    儿童节庆祝代码示例.rar

    2. **图形用户界面(GUI)编程**:如果涉及到创建交互式应用,可能会使用到Tkinter、PyQt或wxPython等库,学习如何设计按钮、文本框等控件。 3. **网页编程**:HTML、CSS和JavaScript,可能用于创建简单的网页游戏...

    MyFirstApp

    Python 以其易学性和广泛的应用领域而闻名,是很多初学者入门编程的选择。 描述 "我的第一个APP" 提示这是一个个人项目,可能是一个简单的移动应用或桌面应用,旨在帮助开发者学习和掌握基本的编程概念和应用程序...

    测试

    在IT行业中,Python是一种广泛应用的高级编程语言,以其简洁、易读的语法和强大的功能而闻名。本话题将深入探讨Python在各种场景下的应用及其重要性。 Python是一种跨平台的解释型语言,它允许开发者快速地编写代码...

    pygenda

    - 支持导入和导出 iCalendar(.ics)文件,与其他日历应用(如 Google 日历、Apple 日历)同步。 - 数据持久化,可能使用 SQLite 数据库存储用户数据。 为了实现这些功能,开发者可能使用了设计模式,如 MVC(模型-...

    python-projects

    5. **图形用户界面(GUI)**:Tkinter是Python的标准GUI库,PyQt和wxPython是更强大的第三方选项。 6. **自动化测试**:unittest和pytest是Python中常用的单元测试框架,确保代码的正确性。 7. **网络编程**:...

    learning_log

    6. **用户界面**:如果项目包含用户界面,可能使用了Tkinter、PyQt或wxPython等Python GUI库,或者使用Web框架的模板系统来创建HTML页面。 7. **数据处理**:对于记录学习进度和分析数据,可能用到Pandas库,它可以...

    HSB-Gold-Price-Bot:使用从恒生银行网站收集的图表自动获取并显示金条价格(XAUHKD)

    它的语法简洁明了,支持多种编程范式,如面向对象、函数式以及过程式编程,这使得Python成为初学者入门编程的首选语言。 在HSB-Gold-Price-Bot项目中,开发者可能使用了Python的网络请求库,如requests或urllib,来...

Global site tag (gtag.js) - Google Analytics