GJS/GNOME Shell扩展:如何实现顶栏按钮文本每60秒自动更新
实现方案
完全可以通过GJS提供的GLib定时器接口实现60秒自动更新需求,以下是修改后的完整可用代码:
const {St, Clutter} = imports.gi; const Main = imports.ui.main; const GLib = imports.gi.GLib; let panelButton; let panelButtonText; // 提升Label到全局作用域方便更新 let timeoutId = null; // 存储定时器ID用于后续销毁 const FILE_PATH = "path/to/myfile.txt"; // 替换为你的实际文件路径 // 封装更新文本的独立函数 function updateFileContent() { try { const fileContents = String(GLib.file_get_contents(FILE_PATH)[1]); panelButtonText.set_text(fileContents.trim()); } catch (e) { panelButtonText.set_text("读取失败"); log(`读取文件失败: ${e.message}`); } return GLib.SOURCE_CONTINUE; // 保持定时器持续运行 } function init () { panelButton = new St.Bin({ style_class : "panel-button", }); panelButtonText = new St.Label({ text : "加载中...", y_align: Clutter.ActorAlign.CENTER, }); panelButton.set_child(panelButtonText); } function enable () { Main.panel._centerBox.insert_child_at_index(panelButton, 2); // 初始化时先读取一次内容 updateFileContent(); // 添加60秒间隔定时器,单位为秒 timeoutId = GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 60, updateFileContent); } function disable () { Main.panel._centerBox.remove_child(panelButton); // 销毁定时器,避免扩展禁用后仍后台运行 if (timeoutId) { GLib.source_remove(timeoutId); timeoutId = null; } }
核心改动说明
- 把文本Label和定时器ID提升到全局作用域,方便更新文本和后续清理资源
- 封装了
updateFileContent函数处理文件读取和文本更新逻辑,增加了错误捕获避免文件异常导致扩展崩溃 - 在
enable阶段添加60秒间隔的全局定时器,初始化时先执行一次读取避免显示初始占位符过久 - 在
disable阶段主动销毁定时器,避免资源泄漏和异常运行
内容的提问来源于stack exchange,提问作者karol
相关产品推荐
相关产品推荐

