gpt4 book ai didi

python - 只读 tkinter 文本小部件

转载 作者:太空狗 更新时间:2023-10-30 00:50:27 26 4
gpt4 key购买 nike

我想将 tkinter text widget 用作 readonly 小部件。它应该充当 transcript 区域。我的想法是将这个抄本保存在一个文件中,每当用户写任何东西时,只需删除小部件的所有内容,然后再次重写。

代码如下所示:

transcript_entry = SimpleEditor()  # SimpleEditor is inherited from ScrolledText
transcript_entry.text.delete("1.0", END)

# this is just a test string, it should be the contents of the transcript file
transcript_entry.text.insert("1.0", "This is test transcript")
transcript_entry.text.bind("<KeyPress>", transcript_entry.readonly)

readonly 函数看起来像:

def readonly(self, event):
self.text.delete("1.0", END)
# this is just a test string, it should be the contents of the transcript file
self.text.insert("1.0", "This is test transcript")

这里的错误是用户输入的最后一个字符被添加到成绩单中。我怀疑原因是调用了只读函数,然后将用户输入写入小部件。如何反转此顺序并让 readonly 函数在 用户输入写入小部件后调用?

有什么提示吗?

最佳答案

插入最后一个字符的原因是默认绑定(bind)(导致插入)发生在您放置在小部件上的自定义绑定(bind)之后。因此,您的绑定(bind)首先触发,然后默认绑定(bind)插入字符。这里还有其他问题和答案可以更深入地讨论这个问题。例如,参见 https://stackoverflow.com/a/11542200/

但是,有一种更好的方法可以完成您正在尝试做的事情。如果要创建只读文本小部件,可以将 state 属性设置为 "disabled"。这将阻止所有插入和删除(并且意味着您需要在任何时候想要以编程方式输入数据时恢复状态)。

在某些平台上,您似乎无法突出显示和复制文本,但这只是因为默认情况下小部件不会在鼠标单击时获得焦点。通过添加绑定(bind)来设置焦点,用户可以突出显示和复制文本,但不能剪切或插入。

这是一个使用 python 2.x 的例子;对于 3.x,您只需更改导入:

import Tkinter as tk
from ScrolledText import ScrolledText

class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
t = ScrolledText(self, wrap="word")
t.insert("end", "Hello\nworld")
t.configure(state="disabled")
t.pack(side="top", fill="both", expand=True)

# make sure the widget gets focus when clicked
# on, to enable highlighting and copying to the
# clipboard.
t.bind("<1>", lambda event: t.focus_set())

if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()

关于python - 只读 tkinter 文本小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21873195/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com