Lee Exothermix
Lee Exothermix

Reputation: 356

tkinter - replace icon for child window

I would like to replace the default python tkinter icon for both a top level window and a child window. I've tried several things that cause errors. What is the best way to replace the icons for both parent and child windows? See my attempts below - I'm using python 3.9.1

import tkinter as tk
from PIL import Image, ImageTk
m = tk.Tk()
m.title('Main Window')
m.geometry('300x100')
blankImageObject = tk.PhotoImage(file='icons/blankIcon.png')
m.tk.call('wm', 'iconphoto', m._w, blankImageObject)

c = tk.Tk('m')
c.title('Child Window')
c.geometry('300x100')

#try to re-use the same image object created for the main window
#c.tk.call('wm', 'iconphoto', c._w, blankImageObject)

#try creating a new PhotoImage object
#c.tk.call('wm', 'iconphoto', c._w, tk.PhotoImage(file='icons/blankIcon.png'))

#try using main window instead of the child window in the Tcl call
#c.tk.call('wm', 'iconphoto', m._w, tk.PhotoImage(file='icons/blankIcon.png'))

#try using main window in the Tcl call and the blankImageObject from the main window
#c.tk.call('wm', 'iconphoto', m._w, blankImageObject)

m.mainloop()

Upvotes: 0

Views: 303

Answers (1)

martineau
martineau

Reputation: 123541

You can do it by creating a new PhotoImage object, but you need to specify the proper Tk instance when you do so by specifying it via the master= keyword argument, as illustrated below:

I also suggest you read Why are multiple instances of Tk discouraged?

import tkinter as tk
from PIL import Image, ImageTk

icon_filepath='icons/blankIcon.png'

m = tk.Tk()
m.title('Main Window')
m.geometry('300x100')

blankImageObject = tk.PhotoImage(file=icon_filepath)
m.tk.call('wm', 'iconphoto', m._w, blankImageObject)

c = tk.Tk('m')
c.title('Child Window')
c.geometry('300x100')

# Create a new PhotoImage object
blankImageObject2 = tk.PhotoImage(master=c, file=icon_filepath)
c.tk.call('wm', 'iconphoto', c._w, blankImageObject2)

m.mainloop()

Upvotes: 1

Related Questions