First Steps第一步
In this part of the wxPython tutorial, we will create some simple examples
本節教程中,我們創建一些簡單的例子。
Simple example簡單例子
We start with a very simple example. Our first script will only show a small window. It won't do much. We will analyze the script line by line. Here is the code
我們從最簡單的例子開始,第一段代碼只顯示一個小窗口。不要緊,我們將一行一行進行代碼分析。
import wx
app = wx.App()
frame = wx.Frame(None,-1,"simple.py")
frame.Show()
app.MainLoop()
frame.Show()
wx.Frame
wx.Frame widget is one of the most important widgets in wxPython. It is a container widget. It means that it can contain other widgets. Actually it can contain any window that is not a frame or dialog. wx.Frame consists of a title bar, borders and a central container area. The title bar and borders are optional. They can be removed by various flags.
wx.Frame是wxPython中最重要的部件。它是一個窗口,意思是它可以包含其它部件。實際上它可以包含任意窗口或者對話框。wx.Frame包括一個標題欄,邊界,中心區域。標題與邊界是可選的。
wx.Frame has the following constructor. As we can see, it has seven parameters. The first parameter does not have a default value. The other six parameters do have. Those four parameters are optional. The first three are mandatory.
wx.Frame具有以下構造函數。像我們看到的,它有七個參數。第一個參數沒有默認值,其它六個都有,四個參數可選,頭三個是強制性的。
wx.Frame(wx.Window parent, int id=-1, string title='', wx.Point pos = wx.DefaultPosition,
wx.Size size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE, string name = "frame")
import wx
app = wx.App()
window = wx.Frame(None,style=wx.MAXIMIZE_BOX|wx.RESIZE_BORDER
|wx.SYSTEM_MENU|wx.CAPTION|wx.CLOSE_BOX)
window.Show()
app.MainLoop()
看上面這段代碼,運行起來時,窗口沒有了最小化。
Size and Position尺寸與位置
We can specify the size of our application in two ways. We have a size parameter in the constructor of our widget. Or we can call the SetSize() method.
有兩個方法可以指定程序的大小:1.用指定的參數指定大小;2.用SetSize()方法
import wx
class Example(wx.Frame):
def __init__(self,parent,title):
super(Example,self).__init__(parent,title=title,size=(250,200))
self.Show()
if __name__ == '__main__':
app = wx.App()
Example(None,title='Size')
app.MainLoop()
def __init__(self,parent,title):
super(Example,self).__init__(parent,title=title,size=(250,200))
同樣地:我們可以指定程序的位置。
import wx
class Example(wx.Frame):
def __init__(self,parent,title):
super(Example,self).__init__(parent,title=title,size=(250,200))
self.Move((800,250))
self.Show()
if __name__ == '__main__':
app = wx.App()
Example(None,title='Size')
app.MainLoop()
Centering on the screen
If we want to center our application on the screen, wxPython has a handy method. The Centre()
method simply centers the window on the screen. No need to calculate the width and the height of the screen. Simply
call the method.
import wx
class Example(wx.Frame):
def __init__(self,parent,title):
super(Example,self).__init__(parent,title=title,size=(250,200))
self.Centre()
self.Show()
if __name__ == '__main__':
app = wx.App()
Example(None,title='Size')
app.MainLoop()