BlenderのPythonスクリプトで、オンとオフを切り替える「トグルボタン(Toggle Button)」を作成する方法
ボタンが押されると、処理Aが行われ、ボタンは押された状態のままになり。
もう一度ボタンが押されると、処理Bが行われ、ボタンは元の状態に戻る。
というUIのボタンです。
ソースコード
- import bpy
- bpy.types.Scene.testBool = bpy.props.BoolProperty(name = 'test Bool', default = False)
- class TestOperator(bpy.types.Operator):
- bl_idname = 'test.test_operator'
- bl_label = 'Test Operator'
- def execute(self, context):
- if bpy.context.scene.testBool == False:
- print('Button Pressed')
- bpy.context.scene.testBool = True
- else:
- print('Button Un Pressed')
- bpy.context.scene.testBool = False
- return{'FINISHED'}
- class TestPanel(bpy.types.Panel):
- bl_space_type = 'VIEW_3D'
- bl_region_type = 'UI'
- bl_category = 'TestTab'
- bl_label = 'Test Toggle'
- def draw(self, context):
- layout = self.layout
- if bpy.context.scene.testBool == True:
- btn_text = 'button ON'
- else:
- btn_text = 'button OFF'
- layout.operator('test.test_operator', text = btn_text, depress = bpy.context.scene.testBool)
- def register():
- bpy.utils.register_class(TestOperator)
- bpy.utils.register_class(TestPanel)
- def unregister():
- bpy.utils.unregister_class(TestOperator)
- bpy.utils.unregister_class(TestPanel)
- if __name__ == '__main__':
- register()
解説
33行目のlayout.operatorの"depress"が、ボタンが押された状態かどうかを設定するプロパティになります。
そこに、Bool値の変数を入れることで、押された状態を任意に変更できるようにしています。
そのBool値は、3行目のbpy.types.Scene.testBoolで宣言しています。
また、9行目のtestOperatorクラスのexecute関数内でこのBool値によって処理内容が分かれるようにし、
12行目、15行目でそれぞれの処理の後に、このBool値が反転するようにして、ボタンと処理内容が連動するようにしています。
28行目~31行目では、ボタンに表示するテキストがBool値によって切り替わるようにbtn_textに設定し、こちらも33行目のtextに代入しています。
0 件のコメント:
コメントを投稿