[Python] Can't use PIL in Python when the script is inside of the Windows Startup-folder

Discussão em 'Python' iniciado por Stack, Fevereiro 20, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to make a simple python script that is not working when it is in the folder: "C:/Users/UserName/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup" in windows 10

    So I have made a python script without console (.pyw), which is run when the pc starts and the user has logged in. After that, a Tkinter fullscreen topmost window will appear with an image on it. The script has to be in the Startup-folder to run when the user has started the pc and logged in. Inside the startup-folder is also a .jpg image which is the one that should be showing.

    The problem is that if I run the script manually from inside the Startup-folder everything works, but when I restart the pc and log in, the Tkinter window doesn't open, and instead the Windows image viewer program opens up showing the desired picture, but not a Tkinter window.

    This is probably because if I run this code inside the folder by manually double clicking the script I get this result:

    from pathlib import Path

    Path.cwd() #Should give the file path from C: to the running script


    C:/Users/UserName/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup
    ​

    While if I keep this script in the folder and restart the pc instead I get this result:


    C:/WINDOWS/System32
    ​

    This must mean that when I run the script manually it will run via the first file path, while if I restart the PC it runs it through another file path. This might be somehow interfering with my code.

    The reason why the Windows image viewer program shows the image has maybe something to do with .show(), which is the line of code that opens the Windows image viewer program to show the image with the variable name .

    This is the code with added comments:

    import tkinter as tk
    from PIL import ImageTk, Image

    root = tk.Tk()

    root.attributes('-fullscreen',1) # Making the window fullscreen
    root.attributes('-topmost',True) # Making the window topmost
    root.title('<title>')

    image = ImageTk.PhotoImage(Image.open('Image.png') # This is the code line that is maybe causing the problem

    label = tk.Label(root, image=image) # Placing the image on the screen
    label.image = image
    label.place(x=<x>, y=<y>)

    root.mainloop()


    This script runs perfectly if you have it anywhere but the startup folder, for example, if you have it on your desktop you can successfully run the script.

    I have tried to eliminate this problem for the better part of a day but have been unsuccessful.

    I have tried changing

    ImageTk.PhotoImage(Image.open('Image.png'))


    to

    file = 'Image.png'
    tk.PhotoImage(file=file)


    to no avail.

    Continue reading...

Compartilhe esta Página