在 Tkinter 輸入小元件中獲取游標位置


我們已經熟悉各種輸入表單,各種單條目欄位用於捕獲使用者輸入。使用 Tkinter,還可以使用 Entry 小元件建立一個單一輸入欄位。使用者在 Entry 欄位中輸入的每個字元都已編制索引。因此,可以使用 index() 方法檢索此索引以獲取游標的當前位置。要檢索游標的當前位置,可以在此函式中傳遞 INSERT 引數。

示例

# Import required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter window
win = Tk()
win.geometry("700x350")
win.title("Get the Cursor Position")

# Create an instance of style class
style=ttk.Style(win)

# Function to retrieve the current position of the cursor
def get_current_info():
   print ("The cursor is at: ", entry.index(INSERT))

# Create an entry widget
entry=ttk.Entry(win, width=18)
entry.pack(pady=30)


# Create a button widget
button=ttk.Button(win, text="Get Info", command=get_current_info)
button.pack(pady=30)

win.mainloop()

輸出

執行上述程式碼將顯示一個帶有一個 Entry 小元件和一個用於獲取游標當前索引的按鈕的視窗。

在 Entry 小元件中輸入一些文字並單擊“獲取資訊”按鈕。它將在控制檯上打印出游標的當前位置。

The cursor is at: 15

更新於: 22-Dec-2021

4K+ 瀏覽量

開啟你的職業

透過完成課程獲得認證

開始
廣告