Enrique Metner
Enrique Metner

Reputation: 189

tkinter: same icon for every window

I have a main root window and I set an icon to an image but when I create a toplevel the icon is not the same which the root window has. So I have to set the icon for it as well. However I have a lot of toplevels and it is a pain to specify for each toplevel what the icon should be. Is there a shortcut to automaticall set the icon of a toplevel as soon as it is created?

root = Tk()
root.iconbitmap('img.ico')

top1 = toplevel(root)
top1.iconbitmap('img.ico')
top2 = toplevel(root)
top2.iconbitmap('img.ico')
top3 = toplevel(root)
top3.iconbitmap('img.ico')
# ...

root.mainloop()

Upvotes: 1

Views: 969

Answers (2)

Reblochon Masque
Reblochon Masque

Reputation: 36652

You can subclass tk.Toplevel to encapsulate the desired behavior, and pass it the proper icon:

Maybe like this:

import tkinter as tk


class TopIco(tk.Toplevel):
    def __init__(self, icon_path):
        super().__init__()
        self.iconbitmap(icon_path)

root = tk.Tk()
icon_path = 'im.ico'

root.iconbitmap('icon_path')
top1 = TopIco(root, icon_path)
top2 = TopIco(root, icon_path)
top3 = TopIco(root, icon_path)
# ...

root.mainloop()

You can add other common attributes of the Toplevels you need to your custom class TopIco

[edit] from @acw1668 in the comments (thanks):
parent is optional (implicit) for tk.Toplevel, but there are cases where the following will be needed instead:

class TopIco(tk.Toplevel):
    def __init__(self, parent, icon_path):
        super().__init__(self, parent)
        self.iconbitmap(icon_path)

Upvotes: 3

acw1668
acw1668

Reputation: 46669

You can use root.iconphoto(True, ...) (first argument set to True) to set the icon of the root window and then same icon will be used in subsequent created windows:

import tkinter as tk

root = tk.Tk()
root.title('Root')

icon = tk.PhotoImage(file='trash.png')
root.iconphoto(True, icon)

top = tk.Toplevel()
top.title('Toplevel')

root.mainloop()

The result:

enter image description here

Upvotes: 4

Related Questions