如何配置 Tkinter 文字控制元件中的預設滑鼠雙擊行為?


Tkinter 中的文字控制元件用於在應用程式中新增類似文字編輯器的功能。文字控制元件支援來自使用者的多行使用者輸入。我們可以使用 configure() 方法配置文字控制元件屬性,例如字型屬性、文字顏色、背景等。

文字控制元件還提供了標記,透過該標記我們可以選擇文字。為了擴充套件此功能,我們還可以繫結雙擊按鈕,它將擁有每次選擇一個單詞的事件。

示例

讓我們看一個示例,其中我們停用了滑鼠雙擊按鈕以選擇文字。

# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the tkinter window
win.geometry("700x350")

# Define a function to get the length of the current text
def select_all():
   text.tag_add("start", "1.0", "end")
   return "break"

# Create a text widget
text = Text(win, width=50, height=10, font=('Calibri 14'))
text.pack()
text.insert(INSERT, "Select a word and then double-click")

# Bind the buttons with the event
text.bind('<Double-1>', select_all)

win.mainloop()

輸出

執行以上程式碼將顯示一個帶有預定義文字的文字控制元件。現在,選擇一個單詞並雙擊它以選擇該單詞。

更新於: 06-8 月-2021

541 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告