如何清除/删除Tkinter Text小部件的内容?

Fah*_*lis 27 python tkinter text-widget

我正在TKinterUbuntu上编写一个Python程序来导入和打印Textwidget中特定文件夹中的文件名.它只是将文件名添加到Text 窗口小部件中的先前电影名称,但我想首先清除它,然后添加一个新的文件名列表.但我正在努力清除Text小部件以前的文件名列表.

有人可以解释如何清除Text小部件吗?

屏幕截图和编码如下:

截图显示带有内容的文本小部件

import os
from Tkinter import *

def viewFile():
    path = os.path.expanduser("~/python")
    for f in os.listdir(path):
        tex.insert(END, f + "\n")

if __name__ == '__main__':
    root = Tk()

    step= root.attributes('-fullscreen', True)
    step = LabelFrame(root, text="FILE MANAGER", font="Arial 20 bold italic")
    step.grid(row=0, columnspan=7, sticky='W', padx=100, pady=5, ipadx=130, ipady=25)

    Button(step, text="File View", font="Arial 8 bold italic", activebackground=
           "turquoise", width=30, height=5, command=viewFile).grid(row=1, column=2)
    Button(step, text="Quit", font="Arial 8 bold italic", activebackground=
           "turquoise", width=20, height=5, command=root.quit).grid(row=1, column=5)

    tex = Text(master=root)
    scr=Scrollbar(root, orient=VERTICAL, command=tex.yview)
    scr.grid(row=2, column=2, rowspan=15, columnspan=1, sticky=NS)
    tex.grid(row=2, column=1, sticky=W)
    tex.config(yscrollcommand=scr.set, font=('Arial', 8, 'bold', 'italic'))

    root.mainloop()
Run Code Online (Sandbox Code Playgroud)

Fah*_*lis 54

我只是添加了"1.0"来检查我的身体并开始工作

tex.delete('1.0', END)
Run Code Online (Sandbox Code Playgroud)

你也可以试试这个

  • `1.0` 或 `'1.0'` 都可以工作。确保小部件的状态设置为正常,`tex.config(state=NORMAL)`。 (4认同)
  • @NeoNØVÅ7 `END` 仅当您执行 `from Tkinter import *` 时才有效。如果您还没有从 Tkinter 导入所有内容,那么您需要执行“tk.END”。 (4认同)
  • 谢谢,一旦我意识到我需要做tex.config(state = NORMAL)才能删除它. (2认同)

小智 15

根据tkinterbook,清除文本元素的代码应该是:

text.delete(1.0,END)
Run Code Online (Sandbox Code Playgroud)

这对我有用.资源

它与清除入口元素不同,这是这样做的:

entry.delete(0,END)#note 0而不是1.0


lox*_*sat 8

from Tkinter import *

app = Tk()

# Text Widget + Font Size
txt = Text(app, font=('Verdana',8))
txt.pack()

# Delete Button
btn = Button(app, text='Delete', command=lambda: txt.delete(1.0,END))
btn.pack()

app.mainloop()
Run Code Online (Sandbox Code Playgroud)

这是一个txt.delete(1.0,END)如上所述的例子。

的使用lambda使我们能够在不定义实际函数的情况下删除内容。


Sai*_*i N 6

这有效

import tkinter as tk
inputEdit.delete("1.0",tk.END)
Run Code Online (Sandbox Code Playgroud)