我有这段代码来使每个文本"可点击",来自具有tkinter的Text()小部件. 然而,当我运行程序并点击一个文本时,我得到了这个错误消息,每个错误消息都对应 文本行:

_tkinter.TclError: bad text index "This is the first string.". _tkinter.TclError: bad text index "This is the second string.". 一百零二

如果现在有人能有办法解决这个问题,我将永远感激.以下是完整的代码:

import tkinter as tk

def text_click(event):
    index = text_widget.tag_names(tk.CURRENT)[0]
    clicked_text = text_widget.get(index)
    print(clicked_text)

# Create the main window
window = tk.Tk()

# Create a Text widget
text_widget = tk.Text(window, wrap="word")
text_widget.pack()

# List of strings
texto = ["This is the first string.", "This is the second string.", "This is the third string."]

# Insert each string from the list
for string in texto:
    text_widget.insert(tk.END, string + "\n")

    # Apply a tag to each inserted string
    tag_start = f"{text_widget.index(tk.END)}-{len(string) - 1}c"
    tag_end = f"{text_widget.index(tk.END)}-1c"
    text_widget.tag_add(string, tag_start, tag_end)

    # Bind the click event to the tag
    text_widget.tag_bind(string, "<Button-1>", text_click)

# Make the text widget read-only
text_widget.configure(state="disabled")

# Start the tkinter event loop
window.mainloop()

我希望打印每一行的文本时,点击它.

推荐答案

您可以这样修改您的text_click函数:

def text_click(event):
    index = text_widget.index(tk.CURRENT)
    clicked_text = text_widget.get(index + " linestart", index + " lineend")
    print(clicked_text)

这将使用text_widget.index(tk.CURRENT)检索所点击文本的索引,然后使用该索引通过向索引添加适当的linestartlineend修饰符来检索实际文本.

Python相关问答推荐

调试回归无法解决我的问题

如何判断. text文件中的某个字符,然后读取该行

合并同名列,但一列为空,另一列包含值

两极:如何分割一个大 pyramid 并并行保存每个

sys.modulesgo 哪儿了?

从 struct 类型创建MultiPolygon对象,并使用Polars列出[list[f64]列

如何让pyparparsing匹配1天或2天,但1天和2天失败?

更改Seaborn条形图中的x轴日期时间限制

使用多个性能指标执行循环特征消除

优化在numpy数组中非零值周围创建缓冲区的函数的性能

仅从风格中获取 colored颜色 循环

在内部列表上滚动窗口

更改matplotlib彩色条的字体并勾选标签?

使用索引列表列表对列进行切片并获取行方向的向量长度

为什么符号没有按顺序添加?

数据抓取失败:寻求帮助

优化器的运行顺序影响PyTorch中的预测

所有列的滚动标准差,忽略NaN

Python—转换日期:价目表到新行

如何按row_id/row_number过滤数据帧