VS Code中settings.json的Python模块导入与self关键字颜色自定义不生效
问题
我基于GitHub Dark主题调整了部分代码颜色以符合个人偏好,但无论进行何种设置,Python的模块导入语句与类中的self关键字始终保持主题默认颜色。请问是否存在设置被覆盖的情况,或是我遗漏了某些配置细节?以下是我的settings.json配置:
{ "python.defaultInterpreterPath": "C:\\Users\\Shayn\\AppData\\Local\\Programs\\Python\\Python311\\python.exe", "python.formatting.provider": "none", "python.analysis.autoImportCompletions": true, "workbench.iconTheme": "eq-material-theme-icons-darker", "workbench.colorTheme": "GitHub Dark", "workbench.colorCustomizations": { "editor.background": "#252323" }, "editor.tokenColorCustomizations": { "textMateRules": [ { "scope": "entity.name.type.module.python", // change not implemented "settings": { "foreground": "#7EBDFF" } }, { "scope": "variable.language.special.self.python", "settings": { "foreground": "#7EBDFF" // change not implemented } }, { "scope": ["variable.parameter", "comment"], "settings": { "fontStyle": "italic" } }, { "scope": "keyword.control.try-except.python", "settings": { "foreground": "#e06c75" } }, { "scope": "entity.name.function", "settings": { "foreground": "#7EBDFF" } }, { "scope": "entity.name.type.class", "settings": { "foreground": "#7EBDFF" } }, { "scope": "punctuation.definition.string.begin", "settings": { "foreground": "#98c379" } }, { "scope": "punctuation.definition.string.end", "settings": { "foreground": "#98c379" } }, { "scope": "string.quoted.single", "settings": { "foreground": "#98c379" } } ] }, }
解决方案
问题出在你使用的语法Scope不匹配,VSCode无法找到对应的代码元素进行样式修改,具体修正如下:
修正模块导入的Scope:
你当前用的entity.name.type.module.python不是模块导入语句的正确Scope。如果要修改导入的模块名称(比如import requests里的requests),应该使用entity.name.module.python;如果需要修改import、from这些关键字的颜色,使用keyword.control.import.python。修正self关键字的Scope:
self的正确Scope是variable.language.self.python,你之前写的variable.language.special.self.python是错误的,无法匹配到类中的self关键字。验证Scope的方法:
按Ctrl+Shift+P打开命令面板,输入Developer: Inspect Editor Tokens and Scopes,点击要查看的代码(比如self或导入的模块),就能看到当前元素对应的所有Scope,确保你的规则使用正确的Scope值。
修改后的对应规则示例:
{ "editor.tokenColorCustomizations": { "textMateRules": [ // 修改导入的模块名称颜色 { "scope": "entity.name.module.python", "settings": { "foreground": "#7EBDFF" } }, // 修改self关键字颜色 { "scope": "variable.language.self.python", "settings": { "foreground": "#7EBDFF" } }, // 其他原有规则保持不变... ] } }
内容的提问来源于stack exchange,提问作者Shayne Lussier
相关产品推荐
相关产品推荐

