Python GUI编程:wxPython模块之按钮和复选框
1. 按钮
按钮是GUI界面中必不可少的一环,在前面Tkinter中已经介绍过按钮,而且大家对按钮一定不陌生,那么我们直接进行语法的学习,wxPython中按钮的语法结构为:
1 | wx.Button(parent,
id
,label,pos,size,style,validator,name) |
它的相关参数与前面我们使用过的参数大致相同,下面我们使用Button按钮对上一节的登录界面进行修饰,代码如下:
1234567891011121314151617 | import wx
class Frame(wx.Frame):
def __init__(
self
):
wx.Frame.__init__(
self
,
None
, wx.ID_ANY,
"登陆"
, size
=
(
300
,
250
))
panel
= wx.Panel(
self
,
-
1
)
wx.StaticText(panel, wx.ID_ANY,
"登录界面"
, (
,
10
),(
150
,
-
1
),wx.ALIGN_RIGHT)
self
.text
= wx.StaticText(panel, wx.ID_ANY,
"账户"
, (
,
50
),(
80
,
-
1
),wx.ALIGN_RIGHT)
self
.text
= wx.StaticText(panel, wx.ID_ANY,
"密码"
, (
,
90
),(
80
,
-
1
),wx.ALIGN_RIGHT)
self
.text
= wx.TextCtrl(panel, wx.ID_ANY, "", (
100
,
50
),(
100
,
20
),wx.ALIGN_LEFT)
self
.text
= wx.TextCtrl(panel, wx.ID_ANY, "", (
100
,
90
), (
100
,
20
), wx.ALIGN_LEFT)
self
.button
= wx.Button(panel, wx.ID_ANY,
"登陆"
, (
70
,
120
),(
50
,
20
),wx.ALIGN_LEFT)
self
.button
= wx.Button(panel, wx.ID_ANY,
"注册"
, (
140
,
120
), (
50
,
20
), wx.ALIGN_LEFT)
if __name__
=
= '__main__'
:
app
= wx.App()
frame
= Frame()
frame.Show(
True
)
app.MainLoop() |
运行图如下:
2. 复选框和单选按钮
复选框对应前面我们学习过的Tkinter中的check控件,复选框提供多个按钮,可提供同时开关的功能,单选按钮对应Tkinter的radio控件,单选按钮提供多个按钮,但是只能选择其中一个按钮,在wxPython中我们使用wx.CheckBox和wx.RadioButton来创建复选框和单选按钮。
看下面的例子(复选框):
12345678910111213 | import wx
class Frame(wx.Frame):
def __init__(
self
):
wx.Frame.__init__(
self
,
None
, wx.ID_ANY,
"复选框"
, size
=
(
300
,
250
))
panel
= wx.Panel(
self
,
-
1
)
self
.box
= wx.CheckBox(panel,
-
1
,
"Checkbox1"
, pos
=
(
50
,
50
), size
=
(
80
,
20
))
# 创建控件
self
.box
= wx.CheckBox(panel,
-
1
,
"Checkbox2"
, pos
=
(
50
,
70
), size
=
(
80
,
20
))
# 创建控件
self
.box
= wx.CheckBox(panel,
-
1
,
"Checkbox3"
, pos
=
(
50
,
90
), size
=
(
80
,
20
))
# 创建控件
if __name__
=
= '__main__'
:
app
= wx.App()
frame
= Frame()
frame.Show(
True
)
app.MainLoop() |
运行结果如图:
单选框代码如下:
1234567891011121314 | import wx
class MyFrame(wx.Frame):
def __init__(
self
):
wx.Frame.__init__(
self
,
None
,
-
1
,
"选择一种喜欢的运动方式"
, size
=
(
300
,
100
))
panel
= wx.Panel(
self
)
wx.StaticText(panel, wx.ID_ANY,
"选择一种喜欢的运动方式"
, (
,
10
), (
200
,
-
1
), wx.ALIGN_RIGHT)
self
.check1
= wx.RadioButton(panel,
-
1
,
"打篮球"
, pos
=
(
60
,
40
), size
=
(
50
,
20
), style
=
wx.RB_GROUP)
self
.check2
= wx.RadioButton(panel,
-
1
,
"打乒乓球"
, pos
=
(
130
,
40
), size
=
(
50
,
20
))
self
.check3
= wx.RadioButton(panel,
-
1
,
"跑步"
, pos
=
(
200
,
40
), size
=
(
50
,
20
))
if __name__
=
= "__main__"
:
app
= wx.App()
frame
= MyFrame()
frame.Show()
app.MainLoop() |
运行图如下:
单选按钮和复选框的使用方式类似,区别在于可不可以多选,这个在我们注册账户,选择信息的时候会经常使用到。
3. 总结
这几种控件与Tkinter的几种控件相对应,大家可以使用两种方法去完成同一个问题,然后找到一种适合自己的。