微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Tkinter 阻止相似的标签连接在一起

如何解决Tkinter 阻止相似的标签连接在一起

我正在开发一个有点模拟表格格式的动态滚动应用程序。不幸的是,由于数据的速度,唯一足够快的方法是文本小部件 (Displaying real time stock data in a scrolling table in Python)。

理想情况下,我想在每个“单元格”周围放置一个边框来模拟表格中的列和行分隔符。但是,如果彼此相邻放置,类似的标签似乎会连接在一起,这意味着边框会延伸到文本小部件的底部

我尝试使用 2 个不同的标签标识符来欺骗它不加入边界,但它仍然合并边界/标签。但是,如果我将颜色甚至 borderwidth 更改为不同的值,它们将不再连接。不幸的是,我需要一个统一的边框宽度。

举个简单的例子,我定义了 3 个标签,2 个属性相同,一个稍微不同(颜色)以显示效果

前两行每个单元格使用2个相同的标签,边框完全合并。

第 4 行显示了正确的边框,但这使用了具有不同属性(颜色)的标签。我想要的功能是具有完全相同的属性,但每个单元格有一个边框:

import tkinter as tk

root = tk.Tk()
text = tk.Text(root)
text.pack()

# Define example tags,2 with identical properties but different identifiers,one with a different property (colour)
text.tag_config("tag1",background="lightgray",borderwidth=1,relief="solid")
text.tag_config("tag2",relief="solid")
text.tag_config("tag3",background="lightyellow",relief="solid")

# Insert 4 example lines
text.insert(tk.INSERT,"Line 1 Cell 1 Line 1 Cell 2 Line 1 Cell 3\n")
text.insert(tk.INSERT,"Line 2 Cell 1 Line 2 Cell 2 Line 2 Cell 3\n")
text.insert(tk.INSERT,"\n")
text.insert(tk.INSERT,"Line 4 Cell 1 Line 4 Cell 2 Line 4 Cell 3\n")

# Different tag identities with same properties "join up",so the borders are
text.tag_add("tag1","1.0","1.14")
text.tag_add("tag2","1.14","1.28")
text.tag_add("tag1","1.28","1.42")

# The tags also merge when on a new line,with the line above
text.tag_add("tag1","2.0","2.14")
text.tag_add("tag2","2.14","2.28")
text.tag_add("tag1","2.28","2.42")

# Line 4 has the correct borders,but only because colour for tag3 is different
text.tag_add("tag1","4.0","4.14")
text.tag_add("tag3","4.14","4.28")
text.tag_add("tag1","4.28","4.42")

root.mainloop()

有没有办法解决这个问题?

解决方法

您无法阻止标签被合并。这是标签如何在 tkinter 中工作的基础。

话虽如此,有很多方法可以模拟列。例如,您可以给每一列一个唯一的标签(“col1”、“col2”等),和/或给每列之间的字符一个标签以在列之间创建一个中断。

注意:当您调用 insert 方法时,您可以提供成对的文本和标签,这样您就不必事后添加标签。

例如,以下函数将在文本小部件的末尾插入三个值,为每列和列分隔符添加标签。如果所有参数都为空,它将插入一个空行以模拟您的示例正在执行的操作。此代码使用标签“col0”、“col1”、“col2”和“sep”,而不是更通用的标签名称。

def insert_row(col0="",col1="",col2=""):
    if col0 == "" and col1 == "" and col2 == "":
        text.insert("end","\n")
    else:
        text.insert("end",col0,"col0","\t","sep",col1,"col1",col2,"col2","\n"
        )

以下是其使用示例:

insert_row("Line 1 Cell 1","Line 1 Cell 2","Line 1 Cell 3")
insert_row("Line 2 Cell 1","Line 2 Cell 2","Line 2 Cell 3")
insert_row()
insert_row("Line 3 Cell 1","Line 3 Cell 2","Line 3 Cell 3")

在以下屏幕截图中,我更改了中间行的颜色以使其突出:

screenshot

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。