【问题标题】:How Do I Replace A Word With Another one In tkinter.Text [duplicate]如何在 tkinter.Text 中用另一个单词替换一个单词 [重复]
【发布时间】:2020-05-20 06:50:21
【问题描述】:

我实际上是在尝试制作一个 Python 编码编辑器,为此我需要制作一个颜色编码系统。例如:'def', 'or', 'if', 'elif', 'else', 'import' 等应该是不同的颜色,因为它们是命令。像这样的:

from tkinter import *
import threading

def colorcommands():
    while True:
        a = textArea.get(0.0, END)
        for f in ["def", "or", "and", "if", "import", "else"]:
            textArea.replace(f, (f, fg="red"))

master = Tk()

textArea = Text()
textArea.pack()

threading.Thread(target=colorcommands).start()

master.mainloop()

但显然这给了我一个错误,因为没有这样的命令。谁能帮帮我?

【问题讨论】:

  • 0.0 是无效索引有两个原因。第一个字符是"1.0",索引应该是字符串。 0.0 有效,因为 tkinter 会将其转换为 "1.0",但使用浮点数在技术上是不正确的。
  • 您的问题不清楚。标题说你想替换文本,但正文说你想突出显示文本。

标签: python python-3.x tkinter tkinter-text


【解决方案1】:

这是最终代码,它运行良好:

from tkinter import *
import threading, keyword

def Process():
    while True:
        a = textArea.get(0.0, END)
        b = a.split("\n")
        words = {}
        for f in range(1, len(b)+1):
            bb = b[f-1].split(" ")
            bb2 = []
            for ff in range(1, len(bb)+1):
                try:
                    bb3 = words[bb[ff-1]]
                    bb3.append(str(f) + "." + str(len(" ".join(bb2))) + " - " + str(f) + "." + str(len(" ".join(bb2)) + len(bb[ff-1]) + 1))
                except:
                    words[bb[ff-1]] = [str(f) + "." + str(len(" ".join(bb2))) + " - " + str(f) + "." + str(len(" ".join(bb2)) + len(bb[ff-1]) + 1)]
                bb2.append(bb[ff-1])

        for f3 in words:
            if f3 in keyword.kwlist:
                for ff in words[f3]:
                    wordss = ff.split(" - ")
                    textArea.tag_add("code", wordss[0], wordss[1])
                    textArea.tag_config("code", foreground="red")

master = Tk()

textArea = Text()
textArea.pack()

threading.Thread(target=Process).start()

master.mainloop()

谢谢大家! :D

【讨论】:

    【解决方案2】:

    我相信您可以通过使用标签来实现这一点。标签可用于更改 Tkinter 中文本的某些部分。首先实际上是使用 tag_configure 配置标签,然后使用 tag_add 应用它。您必须自己查看语法的详细信息。

    我从有相同问题的人那里找到了另一个答案。在接受的答案中,您可以找到示例代码。运行它,看看它是否适合你。 How to change the color of certain words in the tkinter text widget?

    【讨论】:

    • 这很有帮助:)
    猜你喜欢
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-02
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多