Imposta il testo del widget di testo Tkinter con un pulsante
Il widget Text di Tkinter non ha un metodo set dedicato per impostare il contenuto del Text. Deve prima eliminare il contenuto esistente e quindi inserire il nuovo contenuto se dobbiamo modificare completamente il contenuto.
Questo articolo introdurrà come impostare il widget Tkinter utilizzando un pulsante Tkinter.
Codici di lavoro completi per impostare il testo in Text con i metodi delete e insert
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")
Il metodo delete di Text elimina l’intervallo di caratteri specificato nella casella Text, come introdotto nell’articolo di come cancellare il riquadro Text di Tkinter.
1.0 è il primo carattere e "end" è l’ultimo carattere del contenuto nel widget Text. Pertanto, elimina tutto il contenuto all’interno della casella Text.
textExample.insert(1.0, text)
Il metodo insert inserisce il testo nella posizione specificata. Nel codice sopra, inserisce il testo all’inizio.
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 Facebook