如何在 Tkinter 中使一個按鈕既有影像又有文字?
我們可以使用 PhotoImage(影像位置) 函式在 Tkinter 應用程式中載入影像,此函式將影像位置作為引數並將影像顯示在視窗物件上。但是,當我們嘗試將影像新增到按鈕時,它通常會出現在按鈕上,同時隱藏按鈕文字。因此,為了使按鈕文字和圖片相對於彼此,我們通常使用 compound 屬性。它採用四個位置引數之一 - 左、右、上和下,每個引數都定義影像在按鈕上的位置。
示例
在此示例中,我們使用此 影像 將其與按鈕相關聯。
#Import tkinter library from tkinter import * from PIL import Image,ImageTk #Create an instance of Tkinter frame or window win= Tk() #Set the geometry of tkinter frame win.geometry("750x250") #Define a function to close the window def close_win(): win.destroy() #Load the image image = Image.open('preview.png') #Resize the Image image = image.resize((50,50), Image.ANTIALIAS) #Convert the image to PhotoImage img= ImageTk.PhotoImage(image) #Create a Label Label(win, text="Click the below button to close the window",font=('Aerial 15 bold')).pack(pady=20) #Create a label with the image button= Button(win, text="Click Me",font= ('Helvetica 15 bold'),image=img, compound= LEFT, command=close_win) button.pack() win.mainloop()
輸出
以上程式碼將顯示一個視窗,其中包含一個帶有影像和文字標籤的按鈕。當我們單擊按鈕時,它將關閉該視窗。
廣告