リンク

2016年4月25日月曜日

pythonでGUIツールを作る ~ラジオボタン~

pythonでGUIフォームを作成するためのツールキットはいくつか存在します。
中でも「wxPython」はプリインストールされている「tkinter」よりも使い勝手・自由度が高く、人気があるようです。

当ブログではそんな「wxPython」を用いてpythonでGUIツールを作成する方法を少しずつご紹介していきます。

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

今回は、選択系ウィジットの1つである ”ラジオボタン“(RadioButton) をご紹介します。
ラジオボタンは、複数の選択項目をグループ化し、そのグループ内からはひとつしか選択できないようにしたい場合に使用します。

# -*- coding: utf-8 -*-

import wx

app = wx.App()

frame = wx.Frame(None, -1, u'タイトル', size=(200, 200))
panel  = wx.Panel(frame, -1)

# ラジオボタンの設置
radiobutton_1 = wx.RadioButton(panel, -1, 'radiobutton_1', pos=(10,10))
radiobutton_2 = wx.RadioButton(panel, -1, 'radiobutton_2', pos=(10,40))
radiobutton_3 = wx.RadioButton(panel, -1, 'radiobutton_3', pos=(10,70))
radiobutton_4 = wx.RadioButton(panel, -1, 'radiobutton_4', pos=(10,100))

frame.Show()
app.MainLoop()

<結果>

上記スクリプト内で、過去に解説した内容については省略致します。
ご確認いただきたい場合は、wxPythonのススメ ~基礎編~をご覧ください。

続いて詳細を見ていきます。



~~詳細~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ラジオボタンの設置
radiobutton_1 = wx.RadioButton(panel, -1, 'radiobutton_1', pos=(10,10))
ラジオボタンを作成するには、wx.RadioButtonクラスを使用します。

今回の例では引数に(親ウィジット、識別子、表示文字列、表示位置)を指定しています。

RadioButtonクラスでは特に指定がない場合、全ての項目がひとつのグループと見なされます。

今回の例のうち、radiobutton_1とradiobutton_2を1グループ、radiobutton_3とradiobutton_4を別の1グループとしたい場合は次のように記述します。

radiobutton_1 = wx.RadioButton(panel, -1, 'radiobutton_1', pos=(10,10), style=wx.RB_GROUP)
radiobutton_2 = wx.RadioButton(panel, -1, 'radiobutton_2', pos=(10,40))
radiobutton_3 = wx.RadioButton(panel, -1, 'radiobutton_3', pos=(10,70), style=wx.RB_GROUP)
radiobutton_4 = wx.RadioButton(panel, -1, 'radiobutton_4', pos=(10,100))

<結果>

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

ここからは、wx.RadioButtonクラスでよく使用する主な関数をご紹介します。
# 表示文字列を変更する
radiobutton_1.SetLabel(u'ラジオボタン1')

# 無効状態(選択できない状態)にする
radiobutton_1.Disable()

# 有効状態(選択できる状態)にする
radiobutton_1.Enable()

# 選択状態にする
radiobutton_1.SetValue(True)

# 選択していない状態にする
radiobutton_1.SetValue(False)

# ツールチップを設定する
radiobutton_1.SetToolTipString(u'ツールチップ')

# イベントを設定する
radiobutton_1.Bind(wx.EVT_RADIOBUTTON, check_changed)
※check_changedは別途用意する関数を表す。
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

ラジオボタンは、設定の変更や対象の選択など、オンリーワンの選択が必要な場合によく使用しますので、ぜひご参考ください。

==================================================================
環 境:Python 2.7.9 / Windows7
==================================================================
この記事が参考になりましたら、シェア・フォロー・おすすめしていただけると励みになります! \(^o^)/
==================================================================

0 件のコメント:

コメントを投稿