0
0

はじめに

tkinterにてcolorchooserを使用して、Text領域の文字に色を付ける方法を紹介します。
colorchooserを使用することで、カラーパレットを表示しその中から色を選択することが出来るので、柔軟に文字色を変更することが可能です。tkinterを使ってGUIアプリを作成される方の参考になれば幸いです。

開発環境

・WSL2/Ubuntu環境
・Python: 3.10.12

colorchooserを使って文字の色を変える方法

SampleColorText.py

import tkinter as tk
from tkinter import Text, colorchooser


# Applying color to selected text
def Sample_Apply_Color():
    color = colorchooser.askcolor(title="Color-Palet")
    if color:
        selectcolor = color[1]
        area_text.tag_configure(selectcolor, foreground=selectcolor)
        area_text.tag_add(selectcolor, "sel.first", "sel.last")


# configure root
root = tk.Tk()
root.title("ColorText")
root.geometry("800x600")

# configure menu
bar_menu = tk.Menu(root)
list_decoration = tk.Menu(bar_menu, tearoff=0)
bar_menu.add_cascade(label="Decoration", menu=list_decoration)
list_decoration.add_command(label="Color", command=Sample_Apply_Color)
root.config(menu=bar_menu)

# make text
area_text = Text(root, wrap="word", undo=True)
area_text.pack(fill="both", expand=True)

# display window
root.mainloop()

Text領域で文字の色を変更する流れ

①Text領域に文字列を入力します
②Text領域の文字列をマウスなどで選択します
(選択した文字列の色が変わって強調表示されます)
③DecorationタブのColorをクリックし、カラーパレットから色を選択します
④Text領域で選択した文字列がカラーパレットで選択した色に変更されます

参考文献

本記事は以下情報を参考にして執筆しました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0