Tkinter 中的 iconphoto() 方法Python
iconphoto()方法用于设置任何 tkinter/toplevel 窗口的标题栏图标。但是要设置任何图像作为标题栏的图标,图像应该是PhotoImage类的对象。
句法:
iconphoto(self, default = False, *args)
设置图标图像的步骤 -
from tkinter import Tk
master = Tk()
photo = PhotoImage(file = "Any image file")
master.iconphoto(False, photo)
根据通过 args 传递的命名照片图像设置此窗口的标题栏图标。如果默认为True ,这也适用于所有未来创建的顶层。图像中的数据在调用时被作为快照。如果稍后更改图像,这不会反映在标题栏图标中。该函数还将提供的图标缩放到适当的大小。
代码 #1:当提供 PhotoImage 时。
Python3
# Importing Tkinter module
from tkinter import *
from tkinter.ttk import *
# Creating master Tkinter window
master = Tk()
# Creating object of photoimage class
# Image should be in the same folder
# in which script is saved
p1 = PhotoImage(file = 'info.png')
# Setting icon of master window
master.iconphoto(False, p1)
# Creating button
b = Button(master, text = 'Click me !')
b.pack(side = TOP)
# Infinite loop can be terminated by
# keyboard or mouse interrupt
# or by any predefined function (destroy())
mainloop()
Python3
# Importing Tkinter module
from tkinter import *
from tkinter.ttk import *
# Creating master Tkinter window
master = Tk()
# Setting icon of master window
master.iconphoto(False, 'info.png')
# Creating button
b = Button(master, text = 'Click me !')
b.pack(side = TOP)
# Infinite loop can be terminated by
# keyboard or mouse interrupt
# or by any predefined function (destroy())
mainloop()
输出:
例外:如果您直接提供图像而不是 PhotoImage 对象,则会显示以下错误。
代码 #2:当没有提供 PhotoImage 对象时。
Python3
# Importing Tkinter module
from tkinter import *
from tkinter.ttk import *
# Creating master Tkinter window
master = Tk()
# Setting icon of master window
master.iconphoto(False, 'info.png')
# Creating button
b = Button(master, text = 'Click me !')
b.pack(side = TOP)
# Infinite loop can be terminated by
# keyboard or mouse interrupt
# or by any predefined function (destroy())
mainloop()
输出:
Traceback (most recent call last):
File "C:\Users\Admin\Documents\GUI_python\geeks.py", line 14, in
master.iconphoto(False, 'info.png')
File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1910, in wm_iconphoto
self.tk.call('wm', 'iconphoto', self._w, *args)
_tkinter.TclError: can't use "info.png" as iconphoto: not a photo image