iconphoto()方法用於設置任何tkinter /頂層窗口的標題欄圖標。但是要將任何圖像設置為標題欄的圖標,圖像應該是PhotoImage類的對象。
用法:
iconphoto(self, default = False, *args)
設置圖標圖像的步驟-
from tkinter import Tk master = Tk() photo = PhotoImage(file = "Any image file") master.iconphoto(False, photo)
根據通過的命名照片圖像為此窗口設置標題欄圖標args
。如果default
為True,這也將應用於將來創建的所有頂級。圖像中的數據在調用時作為快照。如果以後更改圖像,則不會在標題欄圖標中反映出來。該函數還可以將提供的圖標縮放到適當的大小。
代碼1:提供PhotoImage時。
# 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, '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對象時。
# 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
相關用法
- Python Tkinter resizable()用法及代碼示例
- Python Tkinter minsize()用法及代碼示例
- Python Tkinter grid()用法及代碼示例
- Python Tkinter destroy()用法及代碼示例
- Python Tkinter place()用法及代碼示例
- Python Tkinter pack()用法及代碼示例
- Python Tkinter maxsize()用法及代碼示例
注:本文由純淨天空篩選整理自sanjeev2552大神的英文原創作品 iconphoto() method in Tkinter | Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。