change the icon of a windows shortcut .lnk file using python - python

I want to change the icon of a .lnk file after I have created it. This is my main code so far:
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut("shortcut.lnk")
shortcut.Targetpath = "C:\\Users\Benjie\AppData\Local\Programs\Python\Python36\python.exe"
shortcut.save()
This creates a shortcut with the python icon, but I want to change it to a different icon, if possible, to the icon of a different .exe file.
How can I do this?
I'd preferably use one of the windows api librarys, but if this is not possible, an external library would work aswell.
Thanks

Ok, after a few hours of researching stuff with the help of this, I managed to find what I was looking for: shortcut.IconLocation. This sets the icon of a shortcut to an icon from an .exe, .dll .icl or .ico file. For example:
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortcut("shortcut.lnk")
shortcut.TargetPath = "C:\\Users\Benjie\AppData\Local\Programs\Python\Python36\python.exe"
shortcut.IconLocation = "C:\path_to_.exe,1"
shortcut.Save()
The icon path is a path to the file, with a comma and the number of the icon in the file. You can see the icons for a file if you create a shortcut and change its icon in its properties, Then browse for the file.

Related

Copying the icon of target file to its shortcut in Python

I'm a beginner at programming and recently started experimenting with creating shortcuts using python.
I know how to create a shortcut using win32com client but was wondering how to copy the same icon of the target file to its shortcut that is being created.
To illustrate, here is the code:
import win32com.client
path = r"D:\\meh.lnk"
target = r"D:\\Python\words.txt"
icon = r"" # i dont have any icon to attach here yet.
shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut(path)
shortcut.Targetpath = target
shortcut.IconLocation = icon
So I was wondering how I can set the path of the original target file's icon to the the icon
variable, to attach it to its shortcut, or some other way to achieve the same goal.
I haven't really tried anything yet because i dont know where to start, i did try to put the same path of the target file to the icon variable, but that did not work.
EDIT: Ok so, the solution to this is not to set the IconLocation manually, the icon is set automatically from the target file unless it is set manually.

Run .py file in system tray rather than in taskbar window

I have a .py file that runs via Task Scheduler when I log into my computer, and it's constantly listening for specific keyboard events to happen. Rather than having it run in the Python Console window on the Taskbar, I'd like to get it to run in the system tray with a Python icon to make it more clean.
I have discovered the pysystray library, and can successfully make a Python icon in the system tray with a right-click menu which will allow me to quit the icon.
from os import path as path
import PIL.Image
import pystray
def on_clicked(icon, item):
if str(item) == "Quit":
icon.stop()
dir_path = path.dirname(path.realpath(__file__))
icon_image = "\\Icon\\Python.ico"
full_path = dir_path + icon_image
image = PIL.Image.open(full_path)
icon = pystray.Icon(
"Testing",
image,
menu=pystray.Menu(pystray.MenuItem("Quit", on_clicked)),
)
icon.run()
However, I can't figure out how to get my existing Python file to run under the icon. It seems like there are two separate events happening; one for launching the icon, and another for running the rest of the code. I would want to make sure that if the "Quit" option is chosen, then the .py file would also stop.
Also, it would be really helpful to have a separate right-click menu item which will display either Python cmd line text since it's constantly being overwritten in my main .py file with a print statement.
Any help/insight would be really appreciated!
The pystray.run function accepts an optional callback function as a parameter. The callback function is run in a separate thread and should be closed normally by ln 9: icon.stop().

Python tkinter : browse directory and save to new directory

I would like to open a new browser by clicking Button from python tkinker GUI and new directory need to be saved and display on GUI.
I am able to open current directory with command below;
import os
subprocess.Popen('explorer "C:\temp"')
cur_path = os.path.dirname(__file__)
my question is how to save the active browser dir and display on GUI after Step A/B above?
First of all, the imports needed for this answer:
import os
import tkinter as tk # if using Python 3
import Tkinter as tk # if using Python 2
Let's say that your button has been defined.
Here is some sample code which will get the current directory:
curr_directory = os.getcwd() # will get current working directory
If you're looking to set up a GUI to ask the user to select a file, use:
name = tkinter.tkFileDialog.askopenfilename(initialdir = curr_directory,title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
print(name)
Which will store the file that they have chosen, with the directory they start at set to curr_directory which is the current directory.
If you are instead looking to set up a GUI in which the user chooses a directory, you can use:
dir_name = tk.tkFileDialog.askdirectory()
This will store the name of the directory they have chosen in the dir_name variable.
For more information, check out this link on how to use the file dialog. Alternatively, you can check the general tkinter documentation here (for Python 2) and here (for Python 3). If you need a reference to the file dialog, this is a good source.

In python is there a way to use the windows explorer to create a file path which can then be returned as a string?

I am making a program to manage a database and i need a nice way of choosing the save locations of files within the program. I was wondering if it is possible to open windows explore from my program, select a folder to save a file in, enter the file name and return the file path as a string to the main program.
Look up the Tkinter options in tkFileDialog
I don't think you necessarily need to put together a fully working GUI, you can simply call the method and select a folder location and then use that selected location in your code.
A simplistic example would be:
import Tkinter, tkFileDialog
root = Tkinter.Tk()
x = tkFileDialog.askopenfilename() # Can pass optional arguments for this...
root.destroy()

Use selected explorer file or folder path as a variable in a python script for a contextual menu

I'm writing a python script that takes a file one at a time or recursively through folders and moves them to a new location. The script takes one parameter (the current path of the file). I want to be able to use the selected item in an explorer window as the variable.
I am making a contextual menu through the regedit files that is labeled "Send to Server". I currently have the appropriate regedit files created and pointed to the location of the command python.exe "path\to\python\file.py
long story short, I want a contextual menu to pop up that says "Send to Server" when a file is right clicked and when executed uses the selected file's or folder's path as the only variable I need. So far I have come across tkFileDialog (not quite what I want) ctypes and win32 modules but I can't quite figure out the last three modules or whether or not they will help
As a side note. I have created a python script that does this exact thing on mac osx. Much easier with macs 'services' feature.
If you put a shortcut to this script (written for Python 3) in the user's "SendTo" folder (%USERPROFILE%\SendTo), it will pop up a directory dialog when selected from the right-click SendTo menu. The dialog works for network locations as well. When the script runs, the full path to the selected file/folder is in sys.argv[1]. Currently it just shows the selected destination path in a message box. You can change the extension to pyw if you don't want a console.
import os, sys
from tkinter import Tk, filedialog
from tkinter.messagebox import showinfo
class Dialog:
def __init__(self, path):
self.path = path
self.dst_path = ''
self.root = root = Tk()
root.iconify()
root.after_idle(self.askdirectory)
root.mainloop()
def askdirectory(self):
self.dst_path = filedialog.askdirectory(initialdir=self.path)
showinfo('Selected Path', self.dst_path)
self.root.destroy()
if __name__ == '__main__':
if len(sys.argv) > 1:
path = sys.argv[1]
if os.path.isfile(path):
path = os.path.dirname(path)
dialog = Dialog(path)
#if dialog.dst_path: do_something(dialog.dst_path)

Categories