【问题标题】:How to access the variables of a class - Python如何访问类的变量 - Python
【发布时间】:2021-02-18 00:01:39
【问题描述】:

我有以下代码来使用搅拌器启用文件浏览器:

import bpy
import os
from bpy.props import StringProperty
from bpy_extras.io_utils import ImportHelper
from bpy.types import Operator
sel = ''
class OpenBrowser(bpy.types.Operator):
    bl_idname = "open.file"
    bl_label = "Select Excel File"
    bli_description = "Simulation output excel file"
    filter_glob: StringProperty(default = '*.xls;*.xlsx',options = {'HIDDEN'})
    filepath: bpy.props.StringProperty(subtype="FILE_PATH")
    #somewhere to remember the address of the file

    def execute(self, context):
        global sel
        sel = self.filepath 
        #self.selected_file = self.filepath
        #display = "filepath= "+self.filepath  
        #print(display) #Prints to console  
        #Window>>>Toggle systen console

        return {'FINISHED'}

    def invoke(self, context, event): # See comments at end  [1]
        context.window_manager.fileselect_add(self)
        global sel 
        sel = self.filepath
        #Open browser, take reference to 'self' 
        #read the path to selected file, 
        #put path in declared string type data structure self.filepath

        return {'RUNNING_MODAL'}  
        # Tells Blender to hang on for the slow user input


bpy.utils.register_class(OpenBrowser) 
#Tell Blender this exists and should be used


# [1] In this invoke(self, context, event) is being triggered by the below command
#but in your script you create a button or menu item. When it is clicked
# Blender runs   invoke()  automatically.

#execute(self,context) prints self.filepath as proof it works.. I hope.

bpy.ops.open.file('INVOKE_DEFAULT')
print(sel)

我面临的问题是我已经声明了一个全局变量sel,我想在运行代码时将用户选择的文件路径保存到该变量中。但是,当我运行脚本时,我看到 sel 并没有改变,它就像它被初始化一样。有人可以帮助我如何从班级访问self.filepath 变量吗?我在这里做错了什么?

【问题讨论】:

  • OpenBrowser 的实例在哪里创建?
  • 从调用invoke函数的bpy.ops.open.file('INVOKE_DEFAULT')调用。

标签: python class blender self


【解决方案1】:

如果我理解正确,您想存储该值以备后用。 我不确定为什么 'sel' 在你的情况下甚至没有更新,但我认为更正确的方法是像这样使用 property

import bpy

# Assign a custom property to an existing type.
bpy.types.Scene.my_sel_value = bpy.props.StringProperty(name="Sel")

# Set property value.
bpy.context.scene.my_sel_value = "Foo"

# Get property value.
print(bpy.context.scene.my_sel_value)

可以将属性添加到所有 ID 类型,但对于“全局”值,我们通常使用 bpy.types.scene。尽管一个项目中可以有多个场景,并且它们将具有不同的值。 Blender 关闭时存储属性值。

如果您正在制作插件,您还可以将您的值存储在Addon Preferences。该值对于所有搅拌机项目都是相同的。

【讨论】:

    猜你喜欢
    • 2023-02-15
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多