Come rendere Tkinter Text widget di sola lettura
-
Impostare lo stato
Textsudisableper rendere TkinterTextin sola lettura -
Legare un tasto qualsiasi alla funzione
breakper rendere TkinterTextin sola lettura
Introdurremo dei metodi per rendere il widget Tkinter Text di sola lettura,
- Impostare lo stato
Textper esseredisable - Legare qualsiasi tasto premere per la funzione
break
Impostare lo stato Text su disable per rendere Tkinter Text in sola lettura
Il widget Text diventa di sola lettura dopo che il suo stato è impostato per essere disable.
import tkinter as tk
root = tk.Tk()
readOnlyText = tk.Text(root)
readOnlyText.insert(1.0, "ABCDEF")
readOnlyText.configure(state="disabled")
readOnlyText.pack()
root.mainloop()
Lo stato predefinito di un widget Text è NORMALE, il che significa che l’utente può modificare, aggiungere, inserire o modificare il contenuto del testo in esso contenuto.
readOnlyText.configure(state="disabled")
È necessario modificare lo stato del widget Text in DISABLED per renderlo di sola lettura. Qualsiasi tentativo di modificare il testo all’interno di quel widget sarà silenziosamente ignorato.
disabled a normal se si intende aggiornare il contenuto del widget Text, altrimenti rimane in sola lettura.Legare un tasto qualsiasi alla funzione break per rendere Tkinter Text in sola lettura
Se leghiamo un qualsiasi colpo di tasto alla funzione che restituisce solo la funzione break al widget Text, potremmo ottenere lo stesso risultato che il Text diventa di sola lettura.
import tkinter as tk
root = tk.Tk()
readOnlyText = tk.Text(root)
readOnlyText.insert(1.0, "ABCDEF")
readOnlyText.bind("<Key>", lambda a: "break")
readOnlyText.pack()
root.mainloop()
La differenza tra questa soluzione e la soluzione di cui sopra è che il CTRL+C non funziona qui. Significa che non è possibile né modificare il contenuto né copiarlo.
Dobbiamo fare l’eccezione di CTRL+C alla funzione vincolante per il Text se CTRL+C è desiderato.
import tkinter as tk
def ctrlEvent(event):
if 12 == event.state and event.keysym == "c":
return
else:
return "break"
root = tk.Tk()
readOnlyText = tk.Text(root)
readOnlyText.insert(1.0, "ABCDEF")
readOnlyText.bind("<Key>", lambda e: ctrlEvent(e))
readOnlyText.pack()
root.mainloop()
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