Search code examples
pythonpyqt5systray

Why the icon doesn't display in System Tray although the python code is executing without any error?


I have just started learning python and trying to create a system tray icon. This program is executing without any error but isn't displaying any icon.

from PyQt5.QtGui import * 
from PyQt5.QtWidgets import * 
app = QApplication([]) 
app.setQuitOnLastWindowClosed(False) 
  
# Adding an icon 
icon = QIcon("fb.png") 
  
# Adding item on the menu bar 
tray = QSystemTrayIcon() 
tray.setIcon(icon) 
tray.setVisible(True) 
  
# Creating the options 
menu = QMenu() 
option1 = QAction("Option1") 
option2 = QAction("Option2") 
menu.addAction(option1) 
menu.addAction(option2) 
  
# To quit the app 
quit = QAction("Quit") 
quit.triggered.connect(app.quit) 
menu.addAction(quit) 
  
# Adding options to the System Tray 
tray.setContextMenu(menu) 
app.exec_()

This code displays following output in VSCode

[Running] python -u "e:\python\systray\systray.py"

Solution

  • When you handle external files as the icon then you must use absolute paths either explicit or build them, in your case I assume that the .png is next to the script so you should use:

    import os
    
    CURRENT_DIRECTORY = os.path.dirname(os.path.realpath(__file__))
    #  ...
    icon = QIcon(os.path.join(CURRENT_DIRECTORY, "fb.png"))
    # ...