tkinter -- Text(1)

发布时间:2018-06-06 21:13:26编辑:Run阅读(4588)

    创建第一个 Text

    代码:

    import tkinter as tk
    root = tk.Tk()
    t = tk.Text(root)
    t.pack()
    root.mainloop()

    效果:

    blob.png

    root 中含有一 Text 控件,可以在这个控件内输入文本,可以使用 Ctrl+C/V 向 Text 内添加剪切板上的内容(文本),不接受 Ctrl+Z 执行操作



    向 Text 中添加文本

    代码:

    import tkinter as tk
    root = tk.Tk()
    t = tk.Text(root)
    # 向第一行,第一列添加文本0123456789
    t.insert(1.0, '0123456789')
    # 向第一行,第一列添加文本ABCDEFGHIJ
    t.insert(1.0, 'ABCDEFGHIJ')
    t.pack()
    root.mainloop()

    效果:

    blob.png

    insert 的第一个参数为索引;第二个为添加的内容



    使用 \n来换行

    代码:

    import tkinter as tk
    root = tk.Tk()
    t = tk.Text(root)
    # 向第一行,第一列添加文本0123456789
    t.insert(1.0, '0123456789\n')
    
    # 向第一行,第一列添加文本ABCDEFGHIJ
    t.insert(2.0, 'ABCDEFGHIJ')
    t.pack()
    root.mainloop()

    效果:

    blob.png




    使用内置的 mark 控制添加位置

    mark 是用来表示在 Text 中位置的一类符号

    演示了内置的 mark:INSERT/CURRENT/END/SEL_FIRST/SEL_LAST 的用法

    几个内置的 mark:

    INSERT: 光标的插入点

    CURRENT: 鼠标的当前位置所对应的字符位置

    END: 这个 Text buffer 的最后一个字符

    SEL_FIRST: 选中文本域的第一个字符,如果没有选中区域则会引发异常

    SEL_LAST:选中文本域的最后一个字符,如果没有选中区域则会引发 异常

    代码:

    import tkinter as tk
    root = tk.Tk()
    t = tk.Text(root)
    # 向Text中添加10行文本
    for i in range(1, 11):
        t.insert(1.0, '0123456789\n')
    # 定义各个Button的回调函数,
    # 这些函数使用了内置的mark:INSERT/CURRENT/END/SEL_FIRST/SEL_LAST
    def insertText():
        t.insert(tk.INSERT, 'py3study.com')
    def currentText():
        t.insert(tk.CURRENT, 'py3study.com')
    def endText():
        t.insert(tk.END, 'py3study.com')
    def selFirstText():
        t.insert(tk.SEL_FIRST, 'py3study.com')
    def selLastText():
        t.insert(tk.SEL_LAST, 'py3study.com')
    
    tk.Button(root, text='insert py3study.com ', command=insertText).pack(fill='x')
    tk.Button(root, text='current py3study.com', command=currentText).pack(fill='x')
    tk.Button(root, text='end py3study.com', command=endText).pack(fill='x')
    tk.Button(root, text='sel_first py3study.com', command=selFirstText).pack(fill='x')
    tk.Button(root, text='sel_last py3study.com', command=selLastText).pack(fill='x')
    t.pack()
    root.mainloop()

    效果:

    444.gif




关键字

上一篇: tkinter -- Toplevel

下一篇: tkinter -- Text (2)