如何使用按鈕設定 Tkinter Entry 文字輸入控制元件的文字
Jinku Hu
2024年2月15日
Tkinter
Tkinter Entry

我們有兩種方法可以通過單擊按鈕來設定或更改 Tkinter Entry
文字輸入控制元件的文字,
- Tkinter 的
delete
和insert
方法 - Tkinter 的
StringVar
方法
Tkinter 的 delete
和 insert
方法來設定 Entry
文字輸入控制元件的內容
Tkinter 的 Entry
控制元件沒有專用的 set
方法來設定 Entry
文字輸入的內容。如果我們必須更改內容,它首先需要刪除現有內容,然後插入新內容。
使用 delete
和 insert
方法在文字輸入框中設定文字的完整的工作程式碼
import tkinter as tk
root = tk.Tk()
root.geometry("400x50")
def setTextInput(text):
textExample.delete(0, "end")
textExample.insert(0, text)
textExample = tk.Entry(root)
textExample.pack()
btnSet = tk.Button(
root, height=1, width=10, text="Set", command=lambda: setTextInput("new content")
)
btnSet.pack()
root.mainloop()
textExample.delete(0, "end")
Entry
的 delete
方法刪除在文字輸入框中指定範圍的字元。
0
是 Entry
控制元件中內容的第一個字元,"end"
是內容的最後一個字元。因此,delete(0, "end")
刪除文字輸入框中的所有內容。
textExample.insert(0, text)
insert
方法將文字插入指定位置。在上面的程式碼中,它在開頭插入了 text
。
Tkinter StringVar
方法來設定 Tkinter Entry
控制元件的內容
如果 Tkinter Entry
控制元件的內容已與 StringVar
物件相關聯,則每次更新 StringVar
的值時,它可以自動更改 Tkinter Entry
控制元件的內容。
使用 StringVar 物件在 Entry
中設定文字的完整工作程式碼
import tkinter as tk
root = tk.Tk()
root.geometry("400x50")
def setTextInput(text):
textEntry.set(text)
textEntry = tk.StringVar()
textExample = tk.Entry(root, textvariable=textEntry)
textExample.pack()
btnSet = tk.Button(
root, height=1, width=10, text="Set", command=lambda: setTextInput("new content")
)
btnSet.pack()
root.mainloop()
textEntry = tk.StringVar()
textExample = tk.Entry(root, textvariable=textEntry)
textEntry
是一個 StringVar
物件,它與文字內容關聯,或者與 Entry
控制元件中的 textvariable
選項關聯。
textEntry.set(text)
如果將 textEntry
更新為新值 text
,則與 textvariable
關聯的控制元件將被自動更新。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Jinku Hu