ボタンを使用して Tkinter テキストウィジェットのテキストを設定する方法
Jinku Hu
2020年6月25日
2020年4月1日
Tkinter
Tkinter Text

Tkinter の Text
ウィジェットには、Text
のコンテンツを設定するための専用の set
メソッドがありません。コンテンツを完全に変更する必要がある場合は、まず既存のコンテンツを削除してから、新しいコンテンツを挿入する必要があります。
delete
および insert
メソッドを使用して Text
にテキストを設定するための完全な作業コード
import tkinter as tk
root = tk.Tk()
root.geometry("400x240")
def setTextInput(text):
textExample.delete(1.0,"end")
textExample.insert(1.0, text)
textExample = tk.Text(root, height=10)
textExample.pack()
btnSet = tk.Button(root,
height=1,
width=10,
text="Set",
command=lambda:setTextInput("new content"))
btnSet.pack()
root.mainloop()
textExample.delete(1.0,"end")
Text
の delete
メソッドは、Tkinter Text
ボックスをクリアする方法をクリアします。
1.0
は Text
ウィジェットのコンテンツの最初の文字で、"end"
はコンテンツの最後の文字です。したがって、Text
ボックス内のすべてのコンテンツを削除します。
textExample.insert(1.0, text)
insert
メソッドは指定された位置にテキストを挿入します。上記のコードでは、最初に text
を挿入します。
Author: Jinku Hu
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn