在开发的时候,使用的是托盘图标相对路径,打包后,运行软件会报错。
如何解决这个问题呢?
我们可以引入node.js的path模块,使用绝对路径就不会出现这个问题了。
tray = new Tray(path.join(__dirname, '/images/icon.png'));
例子如下:
const {app,BrowserWindow,Menu,Tray,dialog} = require('electron');
const path = require('path');
let tray;
let contextMenu;
function createWindow(){
win = new BrowserWindow({
show:false,
webPreferences: {
nodeIntegration: true
}
});
win.loadFile('index.html');
//添加托盘图标
// tray = new Tray('./images/icon3.png');//之前用的是相对路径,打包后会报错
tray = new Tray(path.join(__dirname, '/images/icon3.png'));//使用绝对路径,打包后正常
//生成上下文菜单
contextMenu = Menu.buildFromTemplate([
{label:'复制',role:'copy'},
{label:'粘贴',role:'paste'},
{label:'剪切',role:'cut'}
]);
tray.setToolTip('托盘图标提示文本');//鼠标移到托盘图标上会提示这段文本
//托盘图标左键点击事件
tray.on('click',(event)=>{
win.show();
});
//托盘图标右键点击事件
tray.on('right-click',(event)=>{
tray.popUpContextMenu(contextMenu);
});
win.on('ready-to-show',()=>{
win.show();
});
win.on('closed',()=>{
console.log('closed');
win = null;
});
//打开开发者工具
win.webContents.openDevTools();
}
app.allowRendererProcessReuse = true;
app.on('ready',createWindow);
app.on('window-all-closed',()=>{
console.log('window-all-closed');
if(process.platform != 'darwin'){
app.quit();
}
});
app.on('activate',()=>{
console.log('activate');
if(win == null) {
createWindow();
}
});
const path = require('path');
let tray;
let contextMenu;
function createWindow(){
win = new BrowserWindow({
show:false,
webPreferences: {
nodeIntegration: true
}
});
win.loadFile('index.html');
//添加托盘图标
// tray = new Tray('./images/icon3.png');//之前用的是相对路径,打包后会报错
tray = new Tray(path.join(__dirname, '/images/icon3.png'));//使用绝对路径,打包后正常
//生成上下文菜单
contextMenu = Menu.buildFromTemplate([
{label:'复制',role:'copy'},
{label:'粘贴',role:'paste'},
{label:'剪切',role:'cut'}
]);
tray.setToolTip('托盘图标提示文本');//鼠标移到托盘图标上会提示这段文本
//托盘图标左键点击事件
tray.on('click',(event)=>{
win.show();
});
//托盘图标右键点击事件
tray.on('right-click',(event)=>{
tray.popUpContextMenu(contextMenu);
});
win.on('ready-to-show',()=>{
win.show();
});
win.on('closed',()=>{
console.log('closed');
win = null;
});
//打开开发者工具
win.webContents.openDevTools();
}
app.allowRendererProcessReuse = true;
app.on('ready',createWindow);
app.on('window-all-closed',()=>{
console.log('window-all-closed');
if(process.platform != 'darwin'){
app.quit();
}
});
app.on('activate',()=>{
console.log('activate');
if(win == null) {
createWindow();
}
});