文本小部件未使用删除功能清除

2024-10-03 17:15:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个TkinterGUI应用程序,其中一个框架有一个文本小部件,它调用一个函数并将其输出打印到小部件上。现在我有一个名为“activeAlarmButton”的按钮,它可以正确地打印到小部件上,但是当我调用clearText()函数时,它不会删除内容。我尝试过各种格式的delete函数参数,但没有成功。每次我按下按钮,它都会在旧的输出下打印相同的输出。我的其他按钮还没有完成,我只想让这个先工作

class logsPage(tk.Frame):
def __init__(self, parent, controller):
    tk.Frame.__init__(self, parent)

    activeAlarmButton = tk.Button(self, text = "Active Alarms", width=25, command = lambda: [clearText(), showActiveAlarms()])
    activeAlarmButton.configure(bg = "light yellow")
    activeAlarmButton.grid(column=1, row=1)

    allAlarmButton = tk.Button(self, text = "All Alarms", width=25)
    allAlarmButton.configure(bg = "light yellow")
    allAlarmButton.grid(column=1, row=2)

    backButton = tk.Button(self, text = "Go Back", width=25)
    backButton.configure(bg = "light yellow")
    backButton.grid(column=1, row=3)

    alarmText = tk.Text(self, borderwidth=3, relief="sunken")
    alarmText.configure(font=("Courier", 12), undo=True, wrap="word")
    alarmText.grid(column=2, row = 1, rowspan=3)

    sys.stdout = TextRedirector(alarmText, "stdout")

    self.grid_rowconfigure(0, weight=2)
    self.grid_rowconfigure(4, weight=1)
    self.grid_columnconfigure(0, weight=1)
    self.grid_columnconfigure(3, weight=1)

    self.configure(background='light blue')

    def clearText():
        alarmText.delete('1.0', 'end')
        alarmText.update()



class TextRedirector(object):
def __init__(self, widget, tag="stdout"):
    self.widget = widget
    self.tag = tag

def write(self, str):
    self.widget.configure(state="normal")
    self.widget.insert("end", str, (self.tag,))
    self.widget.configure(state="disabled")

def flush(self):
    pass

Tags: self部件configuredeftagcolumnwidget按钮
1条回答
网友
1楼 · 发布于 2024-10-03 17:15:49

问题是TextRedirector类将文本小部件的状态保持为disabled。要删除文本,您首先需要执行TextRedirector所做的操作:将状态设置为normal,在文本小部件上执行操作,然后将状态设置回disabled

示例:

def clearText():
    alarmText.configure(state='normal')
    alarmText.delete('1.0', 'end')
    alarmText.configure(state='disabled')

相关问题 更多 >