如何建立可單擊的 Tkinter Label?
Tkinter 中的 Label 元件用來顯示文字和影像。我們可以將一個 URL 與 Label 元件關聯起來,讓它可以單擊。只要單擊此 Label 元件,它就會在預設瀏覽器中開啟相應的連結。
如果要處理瀏覽器和超連結,我們可以使用 Python 中的 webbrowser 模組。此模組在 Python 擴充套件庫中,可以透過在 shell 中輸入以下命令來安裝:pip install webbrowser
示例
在這個應用程式中,我們建立一個 Label,此 Label 將變成一個指向網頁的超連結。
# Import the required library from tkinter import * import webbrowser # Create an instance of tkinter frame win = Tk() win.geometry("700x350") def open_url(url): webbrowser.open_new_tab(url) # Create a Label Widget label= Label(win, text= "Welcome to TutorialsPoint", cursor= "hand2", foreground= "green", font= ('Aerial 18')) label.pack(pady= 30) # Define the URL to open url= 'https://tutorialspoint.tw/' # Bind the label with the URL to open in a new tab label.bind("<Button-1>", lambda e:open_url(url)) win.mainloop()
輸出
當點選此 Label 時,使用者將被重定向到 Tutorialspoint 的主頁。
廣告