Changing icon for only askopenfilename in tkinter, while hiding the main Tk() window in python

Question:

I want to change the window icon only for askopenfilename window in tkinter, while hiding the main Tk() window, but when I use Tk().iconbitmap("myIcon.ico") before Tk().withdraw(), while icon is changed, the root window is still not gone.

here is my code:

from tkinter import Tk
from tkinter.filedialog import askopenfilename

window_icon = 'icon.ico'[enter image description here][1]


Tk().iconbitmap(window_icon)
Tk().withdraw()  # keep the root window from appearing

filename = str(askopenfilename(title='Select an image file', initialdir='')

If i remove this line: Tk().iconbitmap("myIcon.ico") then it works fine with window spawning but then there is no icon on the window.

I want to remove this root window, as shown in image: https://i.stack.imgur.com/SJm0R.png

Also, please suggest if I can use a PIL code to convert saved jpg file into temp ico file data which can be used instead of myIcon.ico? Because this method of icon changing takes .ico file as input and I am convenient with jpg.

Thankyou

PS: This is my first question on stackoverflow!!!

Asked By: Ishan Jindal

||

Answers:

Actually you have created two instances of Tk():

Tk().iconbitmap(window_icon) # first instance
Tk().withdraw()  # 2nd instance

So you just hide the second instance.

Create single instance of Tk() instead:

root = Tk()
root.withdraw()  # keep the root window from appearing
root.iconbitmap(window_icon)

You can use JPEG image as the icon using Pillow (PIL clone) module:

from tkinter import Tk
from PIL import ImageTk

root = Tk()
window_icon = ImageTk.PhotoImage(file="icon.jpg")
root.iconphoto(True, window_icon)
Answered By: acw1668

Follow these steps,

import tkinter as tk
from tkinter.filedialog import askopenfilename

root = tk.Tk()
root.withdraw()
root.iconbitmap("YOUR_IMAGE.ico")
file = askopenfilename(title="YOUR_WINDOW_TITLE", filetypes=[("text files", "*.txt")])

Hope this will work for you!

Answered By: Zed Unknown