如何獲取 Tkinter 文字框中的輸入
Jinku Hu
2023年1月30日
Tkinter
Tkinter Text
Tkinter Text 文字框控制元件具有 get() 方法以從文字框中返回輸入,該文字框具有 start 位置引數和可選的 end 引數來指定要獲取的文字的結束位置。
get(start, end=None)
如果未指定 end,則僅返回在 start 位置指定的一個字元。
從 Tkinter 文字控制元件獲取輸入的示例程式碼
import tkinter as tk
root = tk.Tk()
root.geometry("400x240")
def getTextInput():
result = textExample.get("1.0", "end")
print(result)
textExample = tk.Text(root, height=10)
textExample.pack()
btnRead = tk.Button(root, height=1, width=10, text="Read", command=getTextInput)
btnRead.pack()
root.mainloop()
result = textExample.get("1.0", "end")
Tkinter 文字框控制元件中第一個字元的位置是 1.0,可以用數字 1.0 或字串"1.0"來表示。
"end"表示它將讀取直到文字框的結尾的輸入。我們也可以在這裡使用 tk.END 代替字串"end"。

從上面的動畫中可以看出,如果我們將 "end" 指定為要返回的文字的結束位置,則會出現一個小問題,它在文字字串的末尾還包含換行符\n。
如果我們不希望在返回的輸入中包含換行符,可以將 get 方法的"end"引數更改為"end-1c"。
"end-1c"表示位置是在"end"之前的一個字元。
從 Tkinter 文字控制元件最後獲取不帶\n 的輸入的示例程式碼
import tkinter as tk
root = tk.Tk()
root.geometry("400x240")
def getTextInput():
result = textExample.get(1.0, tk.END + "-1c")
print(result)
textExample = tk.Text(root, height=10)
textExample.pack()
btnRead = tk.Button(root, height=1, width=10, text="Read", command=getTextInput)
btnRead.pack()
root.mainloop()

在這裡,我們還可以在"end-1c"之外使用 tk.END+"-1c"來刪除最後一個字元-\n,因為 tk.END = "end",所以 tk.END+"-1c"等於"end"+"-1c"="end-1c"。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Jinku Hu
