[Blender2.8]Pythonスクリプトで、Operatorのトグルボタンを作成する方法

2020/06/11

Blender Python

t f B! P L

BlenderのPythonスクリプトで、オンとオフを切り替える「トグルボタン(Toggle Button)」を作成する方法


ボタンが押されると、処理Aが行われ、ボタンは押された状態のままになり。
もう一度ボタンが押されると、処理Bが行われ、ボタンは元の状態に戻る。
というUIのボタンです。

How to create toggle button operator UI in blender python.


ソースコード

  1. import bpy
  2.  
  3. bpy.types.Scene.testBool = bpy.props.BoolProperty(name = 'test Bool', default = False)
  4.  
  5. class TestOperator(bpy.types.Operator):
  6. bl_idname = 'test.test_operator'
  7. bl_label = 'Test Operator'
  8. def execute(self, context):
  9. if bpy.context.scene.testBool == False:
  10. print('Button Pressed')
  11. bpy.context.scene.testBool = True
  12. else:
  13. print('Button Un Pressed')
  14. bpy.context.scene.testBool = False
  15. return{'FINISHED'}
  16.  
  17.  
  18. class TestPanel(bpy.types.Panel):
  19. bl_space_type = 'VIEW_3D'
  20. bl_region_type = 'UI'
  21. bl_category = 'TestTab'
  22. bl_label = 'Test Toggle'
  23. def draw(self, context):
  24. layout = self.layout
  25. if bpy.context.scene.testBool == True:
  26. btn_text = 'button ON'
  27. else:
  28. btn_text = 'button OFF'
  29. layout.operator('test.test_operator', text = btn_text, depress = bpy.context.scene.testBool)
  30. def register():
  31. bpy.utils.register_class(TestOperator)
  32. bpy.utils.register_class(TestPanel)
  33. def unregister():
  34. bpy.utils.unregister_class(TestOperator)
  35. bpy.utils.unregister_class(TestPanel)
  36. if __name__ == '__main__':
  37. 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に代入しています。


ブログ内検索:Search

Translate

ブログ アーカイブ

ラベル

Blogリンクタグ

QooQ