python tkinter Text code example

Example 1: python textbox

from Tkinter import *

root = Tk()
T = Text(root, height=2, width=30)
T.pack()
quote = """HAMLET: To be, or not to be--that is the question:
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune
Or to take arms against a sea of troubles
And by opposing end them. To die, to sleep--
No more--and by a sleep to say we end
The heartache, and the thousand natural shocks
That flesh is heir to. 'Tis a consummation
Devoutly to be wished."""
T.insert(END, quote)
mainloop()

Example 2: text widget get tkinter

contents = text.get(1.0, END)

Example 3: tkinter set text

def set_input(value):
    text.delete(1.0, "END")
    text.insert("END", value)

Example 4: python tkinter ausgabefeld

from Tkinter import *

root = Tk()

w = Label(root, text="Hello Tkinter!")
w.pack()

root.mainloop()

Example 5: python tkinter text

# Code snippets for the Text widget
# ...to select and color text
# ...to re and undo changes
# ...to get cursor position and add code at the position
# ...to use the Font option in a more advanced way
# ...to add a x and y scrollbar
# ...to set a selection color

from tkinter import *
from tkinter.font import Font

def undotext(*event):
    text.edit_undo()

def redotext(*event):
    text.edit_redo()
    
def keycheck(*event):
    if event[0].char == '(':
        position = text.index(INSERT)
        text.insert(position, ')')
        text.icursor(position)
        
def coloredtext(*event):
    if event[0].keysym != 'Shift_L':
        return
    color_font = Font(text_calc, text_calc.cget("font"))
    text_calc.tag_configure("colored", font=color_font, foreground='#FF00FF')
    current_tags = text_calc.tag_names("sel.first")
    if "colored" in current_tags:
        text_calc.tag_remove("colored", "sel.first", "sel.last")
    else:
        text_calc.tag_add("colored", "sel.first", "sel.last")


calcfont = Font(family='Courier', size=14, weight='normal', slant='roman', underline=0, overstrike=0)

frame = Frame(master=tkFenster, bg='#FFFFFF')
frame.place(x=0, y=0, width=100, height=100)

scroll_y = Scrollbar(master=frame_calculator)
scroll_y.place(x=0, y=0, width=15, height=100)

scroll_calc_x = Scrollbar(master=frame_calculator, orient='horizontal')
scroll_calc_x.place(x=0, y=100, 100, height=15)

text = Text(master=frame, bg='#FFFFFF', fg='#000000', font=calcfont, borderwidth=0, undo=True, wrap='none',
            insertbackground='#00FF00', selectbackground='#0000FF', selectforeground='#000000',
            yscrollcommand=scrollc_y.set, xscrollcommand=scroll_x.set)
text.place(x=0, y=0, width=85, height=85)
text.bind('<Control-z>', undotext)
text.bind('<Control-y>', redotext)
text.bind('<KeyRelease>', keycheck)
text.bind('<KeyRelease>', coloredtext)
scroll_y.config(command=text.yview)
scroll_x.config(command=text.xview)