Python-GUI简单实例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dpengwang/article/details/81413375

用python实现一个GUI小程序,一个可以打开txt并写入txt的记事本程序

import wx

def load(event):
    file = open(openfilename.GetValue())
    contents.SetValue(file.read())
    file.close()
def save(event):
    file = open(openfilename.GetValue(),'w')
    file.write(contents.GetValue())
    file.close()

app =  wx.App()
win =  wx.Frame(None,title = "txteditor",size = (420,335))
bkg =  wx.Panel(win)

openbutton  = wx.Button(bkg,label = "Open")
openbutton.Bind(wx.EVT_BUTTON,load)
savebutton  = wx.Button(bkg,label = "Save")
savebutton.Bind(wx.EVT_BUTTON,save)
openfilename = wx.TextCtrl(bkg)
contents  = wx.TextCtrl(bkg,style = wx.TE_MULTILINE|wx.HSCROLL)

hbox = wx.BoxSizer()
hbox.Add(openfilename,proportion = 1,flag = wx.EXPAND)
hbox.Add(openbutton,proportion = 0,flag = wx.LEFT,border =5)
hbox.Add(savebutton,proportion = 0,flag = wx.LEFT,border =5)

vbox =  wx.BoxSizer(wx.VERTICAL)
vbox.Add(hbox,proportion =0,flag = wx.EXPAND|wx.ALL,border =5)
vbox.Add(contents,proportion =1,flag = wx.EXPAND|wx.LEFT|wx.BOTTOM|wx.RIGHT,border =5)

bkg.SetSizer(vbox)
win.Show()

app.MainLoop()

涉及的知识:
1. wx.frame:相当于windows中的window,显示出来的窗口界面,构造方法为
wx.Frame(parent, id, title, pos, size=wx.DefaultSize, style, name)
2. wx.Panel:面板,是窗口的容器,大小通常与frame一样,在其上可以放各种控件,其上的控件可以通过TAB键进行遍历,不要直接在框架上方控件,会造成很多问题,同一个框架上可以放多个面板。wxApp -> wxFrame -> wxPanel -> wxSizer -> wxControl
3. BoxSizer:一种布局控件,分为横向和纵向两种,默认为横向,把要排列的空间Add到其中即可
4. app.MainLoop():让界面一直显示,如果没有这行代码,界面将会一闪消失
5. BoxSizer的Add方法中的参数:proportion参数根据在窗口改变大小时所分配的空间设置的比例;flag参数类似于组件的style参数,可用或运算进行连接,wx.EXPAND标记确保组件会扩展到所分配的空间中,而wx.LEFT..wx.ALL决定边框参数(决定间隔的参数)应用在哪条边

展开阅读全文

没有更多推荐了,返回首页