如何设置保证金或抵消标签?

时间:2018-03-13 17:13:07

标签: python tkinter

我正在尝试在文本小部件中添加一个小的自动边距,但是我很难写出标记。

我有一个文本框,我试图在保留边距的同时在该框中插入文本。

我可以获得插入的文本有一个边距但是当我输入最后一行时,边距消失了。到目前为止,我可以挖掘的是如何编写标记并将其与insert()一起使用,但我希望始终保留边距。

问题:有没有办法在所有行上保留边距,而不仅仅是从文件或字符串中插入的边距?

请注意,同样的问题会扩展到Offset标记,因为在插入文本后输入时会遇到同样的问题。

以下是我在Minimal, Complete, and Verifiable example示例中尝试过的内容。

import tkinter as tk


root = tk.Tk()

text = tk.Text(root, width = 10, height = 10)
text.pack()

text.tag_configure("marg", lmargin1 = 10, lmargin2 = 10)
text.insert("end", "Some random text!", ("marg"))

root.mainloop()

enter image description here

2 个答案:

答案 0 :(得分:2)

不幸的是,在小部件的开头和结尾添加和删除文本的边缘情况使得处理标签变得困难。

如果您的目标是保持边距,一种解决方案是为文本窗口小部件创建代理,以便您可以拦截所有插入和删除,并且每次窗口小部件的内容更改时始终添加边距。

例如,从修改窗口小部件时生成<<TextModified>>事件的自定义窗口小部件开始:

class CustomText(tk.Text):
    def __init__(self, *args, **kwargs):
        tk.Text.__init__(self, *args, **kwargs)

        # create a proxy for the underlying widget
        self._orig = self._w + "_orig"
        self.tk.call("rename", self._w, self._orig)
        self.tk.createcommand(self._w, self._proxy)

    def _proxy(self, command, *args):
        cmd = (self._orig, command) + args
        result = self.tk.call(cmd)

        if command in ("insert", "delete", "replace"):
            self.event_generate("<<TextModified>>")

        return result

(见https://stackoverflow.com/a/40618152/7432

接下来,修改程序以使用此代理强制保证金标记始终应用于整个内容:

def add_margin(event):
    event.widget.tag_add("marg", "1.0", "end")

text = CustomText(root, width = 10, height = 6)
text.bind("<<TextModified>>", add_margin)

答案 1 :(得分:1)

如果您将标记添加到整个文本范围(包括最终的尾随换行符),则您键入的新字符将继承该标记。

添加以下内容,也许它会像您期望的那样工作:

portion = []
for ix, row in df.iterrows():
    if df.loc[ix - 1, 'Labelid']==0 and row['Labelid']==0: 
        portion.append(row)
    else:
        # do stuff on the portion
    portion = []

不幸的是,如果删除窗口小部件中的所有文本,您将失去此功能,但这可以解决。

相关问题