Get icon of root window to be used by second window tkinter

Viewed 591

I was wondering if there is anyway to get the ico file of one window and use it in the same window, without getting to know the icon location.

from tkinter import *

root = Tk()
root.iconbitmap('img/icn.ico')
top = Toplevel()

root.mainloop()

Here I want top to have icon of root without saying top.iconbitmap() or top.iconphoto(), the closest ive got is top.tk.call('wm','iconbitmap') but I dont know what is to be done with this as i couldnt find a understandable documentation.

Why dont I want to use iconbitmap(), its basically that, with tkinter.messagebox you can see the messagebox automatically inherit the icons from the parent widget. I was trying to duplicate this effect. Where if the icon is the default tk icon, then show blank icon or else show the custom icon.

Thanks in advance :D

3 Answers

[I'm using links into the core Tk documentation here. It's much more accurate than the Tkinter docs for most things, and Tkinter is mostly an obvious thin wrapper around it.]

You don't want wm iconbitmap. That's been effectively obsolete for decades; it uses an object class — bitmap — that's not relevant these days as it is monochrome and uses the weirdest format. (Filenames need to be preceded by @ to make them work.)

Instead, you want to manipulate the wm iconphoto of the toplevel windows concerned. These take true photo images (there are many image file formats you can load into them) and you can share them easily.

# Load the image from the file; can also use PNG and other formats
my_image = PhotoImage(file="image.gif")

# Apply the image as the icons
first_toplevel_window.iconphoto(False, my_image)
second_toplevel_window.iconphoto(False, my_image)

Note that how the icon is displayed can vary wildly; it's not under your control.

You can use iconphoto() and set the first argument to True, then the same icon will be used for future created toplevels as well:

import tkinter as tk

root = tk.Tk()

icn = tk.PhotoImage(file='my-icon.png')
root.iconphoto(True, icn)

top = tk.Toplevel(root)

root.mainloop()

If you use the default instead of the bitmap (or first) argument, the icon will automatically be used on all TopLevel windows:

root.iconbitmap('img/icn.ico')         # icon set only on root
root.iconbitmap(bitmap='img/icn.ico')  # same as above
root.iconbitmap(default='img/icn.ico') # icon set on root and all TopLevels
Related