【问题标题】:tkinter - replace icon for child windowtkinter - 替换子窗口的图标
【发布时间】:2021-06-29 16:54:18
【问题描述】:

我想为顶级窗口和子窗口替换默认的 python tkinter 图标。我已经尝试了几件导致错误的事情。替换父窗口和子窗口图标的最佳方法是什么?请参阅下面的尝试 - 我正在使用 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()

【问题讨论】:

  • 您想一次性替换所有窗口?

标签: python tkinter icons


【解决方案1】:

您可以通过创建一个新的PhotoImage 对象来做到这一点,但您需要通过master= 关键字参数指定正确的Tk 实例,如下所示:

我也建议你阅读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()

【讨论】:

    猜你喜欢
    • 2013-10-21
    • 1970-01-01
    • 2018-08-05
    • 2022-10-23
    • 2014-09-26
    • 2010-10-07
    • 1970-01-01
    • 2013-09-18
    相关资源
    最近更新 更多