[英]Tkinter: I can't highlight text in text widget
So I made a text editor using tkinter
and I used tag_config
to highlight the syntax.因此,我使用
tkinter
制作了一个文本编辑器,并使用tag_config
突出显示语法。
CODE代码
#Importing modules
from tkinter import *
#Main Window
Window = Tk()
Window.minsize(400, 550)
##Main Script
#Defs
#Main frame
main = Frame(Window)
#Main text widget
text = Text(main, bd=0, highlightthickness=0, borderwidth=0, bg="#323232", fg="white")
#Configs
text.config(width=55, height=35)
main.config(width=55, height=35)
#Tag config for coloring syntax
text.tag_configure("import", foreground="yellow")
Window.update()
#Packs and places
#main.place(anchor="c", rely=.5, relx=.5)
main.pack(expand=True, fill=BOTH, side="right")
text.pack(expand=True, fill=BOTH)
#Update window
Window.update()
#Window.mainloop()
Window.mainloop()
PROBLEM问题
The tag_configure
is not working in line 23 tag_configure
在第 23 行不起作用text.tag_configure("import", foreground="yellow")
QUESTION问题
Is there a way to fix that?有没有办法解决这个问题? or Is there any way to highlighting text in tkinter?
或者有什么方法可以突出显示 tkinter 中的文本?
EDIT编辑
I add我加
def check_syntax(event):
text.tag_add('import', 1.0, END)
text.bind("<Return>", check_syntax)
on the code but there are 1 problem, when i run the code and type import tkinter
in the text widget for test and press enter the "tkinter" is highlighted too在代码上但有 1 个问题,当我运行代码并在文本小部件中键入
import tkinter
进行测试并按输入时,“tkinter”也突出显示
How to fix that?如何解决?
I believe the reason is that you need to actually add a tag first using the tag_add function.我相信原因是您需要首先使用 tag_add function 添加标签。 You should read this other question with a similar problem.
您应该阅读其他类似问题的问题。 I tried out the code myself and it works.
我自己尝试了代码,它可以工作。 (You'll have to press enter after completing a line)
(你必须在完成一行后按回车)
How to use tkinter tag_config? 如何使用 tkinter tag_config? Python 3.7.3
Python 3.7.3
tag_configure
only configures a tag, it doesn't apply the tag to a range of text. tag_configure
只配置一个标签,它不会将该标签应用于文本范围。 To use the tag you need to call tag_add
and give it a start and end index.要使用标签,您需要调用
tag_add
并给它一个开始和结束索引。 That, or add the tag when calling insert
.那,或者在调用
insert
时添加标签。
For example, this shows how to insert some text, and then apply highlighting to a few characters:例如,这显示了如何插入一些文本,然后将突出显示应用于几个字符:
text.insert("end", "import foo\nimport bar\n")
text.tag_add("import", "1.0", "1.6")
text.tag_add("import", "2.0", "2.6")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.