Pythonシェルのようになり、入力時に特定の単語の色を変更したいプログラムがあります。何か助けはありますか?
質問する
97755 次
4 に答える
29
主なアイデアは、カスタマイズするテキストの部分にタグを適用することです。メソッドを使用して特定のスタイルでタグを作成できます。tag_configure
次に、メソッドを使用して変更するテキストの部分にこのタグを適用する必要がありますtag_add
。メソッドを使用してタグを削除することもできますtag_remove
。
tag_configure
以下は、、tag_add
およびtag_remove
メソッドを使用する例です。
#!/usr/bin/env python3
import tkinter as tk
from tkinter.font import Font
class Pad(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.toolbar = tk.Frame(self, bg="#eee")
self.toolbar.pack(side="top", fill="x")
self.bold_btn = tk.Button(self.toolbar, text="Bold", command=self.make_bold)
self.bold_btn.pack(side="left")
self.clear_btn = tk.Button(self.toolbar, text="Clear", command=self.clear)
self.clear_btn.pack(side="left")
# Creates a bold font
self.bold_font = Font(family="Helvetica", size=14, weight="bold")
self.text = tk.Text(self)
self.text.insert("end", "Select part of text and then click 'Bold'...")
self.text.focus()
self.text.pack(fill="both", expand=True)
# configuring a tag called BOLD
self.text.tag_configure("BOLD", font=self.bold_font)
def make_bold(self):
# tk.TclError exception is raised if not text is selected
try:
self.text.tag_add("BOLD", "sel.first", "sel.last")
except tk.TclError:
pass
def clear(self):
self.text.tag_remove("BOLD", "1.0", 'end')
def demo():
root = tk.Tk()
Pad(root).pack(expand=1, fill="both")
root.mainloop()
if __name__ == "__main__":
demo()
于 2015-05-20T01:54:00.683 に答える
15
チャットクライアントを作成しました。Text
正規表現を使用してタグを適用できる非常に使いやすいカスタムウィジェットを使用して、会話の特定の部分を強調表示しました。これは次の投稿に基づいています:tkinterテキストウィジェットでテキストを強調表示する方法。
ここに使用例があります:
# "text" is a Tkinter Text
# configuring a tag with a certain style (font color)
text.tag_configure("red", foreground="red")
# apply the tag "red"
text.highlight_pattern("word", "red")
于 2013-02-10T23:54:22.350 に答える
11
この例を見てください:
from tkinter import *
root = Tk()
text = Text(root)
text.insert(INSERT, "Hello, world!\n")
text.insert(END, "This is a phrase.\n")
text.insert(END, "Bye bye...")
text.pack(expand=1, fill=BOTH)
# adding a tag to a part of text specifying the indices
text.tag_add("start", "1.8", "1.13")
text.tag_config("start", background="black", foreground="yellow")
root.mainloop()
于 2013-02-09T09:12:02.167 に答える
0
カスタムtkinterウィジェットTextを使用して、正規表現の一致ごとにテキストの色を変更し、「text_changed」に類似したイベントを取得することができました。
import tkinter as tk
class CustomText(tk.Text):
def __init__(self, *args, **kwargs):
"""A text widget that report on internal widget commands"""
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
そして、次のように使用します。
scr = CustomText(w)
scr.tag_configure('red', foreground = 'red')
scr.tag_configure('purple', foreground = '#a820a1')
scr.bind('<<TextModified>>', self.__textchanged__)
def __textchanged__(self, evt):
for tag in evt.widget.tag_names():
evt.widget.tag_remove(tag, '1.0', 'end')
lines = evt.widget.get('1.0', 'end-1c').split('\n')
for i, line in enumerate(lines):
self.__applytag__(i, line, 'red', 'while|if', evt,widget) # your tags here
self.__applytag__(i, line, 'purple', 'True', evt.widget) # with a regex
@staticmethod
def __applytag__ (line, text, tag, regex, widget):
indexes = [(m.start(), m.end()) for m in re.finditer(regex, text)]
for x in indexes:
widget.tag_add(tag, f'{line+1}.{x[0]}', f'{line+1}.{x[1]}')
于 2019-09-20T15:56:48.230 に答える