如何在 Tkinter 中將圖片用作按鈕?


在本例中,我們將在視窗中建立一個圓角按鈕,該按鈕可在建立表單、遊戲、對話方塊等許多其他應用程式中使用。

Tkinter 中建立圓角按鈕的最佳方法是,使用所需的按鈕影像,並將其變成框架內的可點選按鈕。透過使用PhotoImage() 函式可以輕鬆實現,該函式會獲取所需的按鈕影像。

因此,以下步驟可以使所需的影像成為一個按鈕,

  • 首先,我們將建立一個虛擬按鈕,該按鈕可用於使影像可點選。

  • 使用PhotoImage(file) 函式從源影像中獲取影像。

  • 將影像檔案作為 Button 函式中的值傳入

  • 刪除borderwidth=0

  • 現在,就生成了一個圓角按鈕。

對於本例,我們將使用此影像,並使其可點選。

#Import all the necessary libraries
from tkinter import *

#Define the tkinter instance
win= Toplevel()
win.title("Rounded Button")

#Define the size of the tkinter frame
win.geometry("700x300")

#Define the working of the button

def my_command():
   text.config(text= "You have clicked Me...")

#Import the image using PhotoImage function
click_btn= PhotoImage(file='clickme.png')

#Let us create a label for button event
img_label= Label(image=click_btn)

#Let us create a dummy button and pass the image
button= Button(win, image=click_btn,command= my_command,
borderwidth=0)
button.pack(pady=30)

text= Label(win, text= "")
text.pack(pady=30)

win.mainloop()

輸出

執行上述程式碼將產生以下輸出 −

更新日期:15-Sep-2023

32K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告