设置为使用标签加粗所选文本 [英] Set to bold the selected text using tags

查看:39
本文介绍了设置为使用标签加粗所选文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力制作一个简单的文本编辑器,并且一直在尝试使用标签.我已经能够使用标签创建理由.现在我要添加一个粗体选项.

I have been working trying to make a simple text editor, and have been experimenting with tags. I have been able to create justifying using tags. Now I'm adding a bold option.

我的问题是我找不到很多使用 "sel" 标签的例子,这个标签用于当前选择.

My problem is that I can't find many examples of using the "sel" tag, a tag used on current selection.

每当我使用 SEL 标签时,文本只有在突出显示时才会显示为粗体,当它不突出显示时,它会恢复为旧的细字体.

Whenever I use the SEL tag, the text is only bold as long as it is highlighted, when it becomes un-highlighted, it reverts back to its old skinny font.

这是我代码的一小部分:

This is a small portion of my code:

def Bold(self, body, Just, Line, selected font):
    bold font = tkFont.Font(family=selectedfont, weight="bold")
    selected font = boldfont
    body.tag_config("sel",font=selectedfont)
    body.tag_add("sel", 1.0,END)

Bold 按钮被按下时,前一个函数被调用.现在,我将 body.tag_add("sel", 1.0, END)1.0 设置为 END,因为我没有知道如何获取选定的域.我试过<<>,但是试了很久还是没有用.

When the Bold button is pressed, the previous function is called. Right now, I have the body.tag_add("sel", 1.0, END) set from 1.0 to END, because I don't know how to get the selected domain. I've tried <<Selection>>, but after experimenting for a long time, it hasn't helped me.

推荐答案

你只需要在你的函数内部使用 tag_add() :

You would only need tag_add() inside of your function:

import Tkinter as tk

def make_bold():
    aText.tag_add("bt", "sel.first", "sel.last")

lord = tk.Tk()

aText = tk.Text(lord, font=("Georgia", "12"))
aText.grid()

aButton = tk.Button(lord, text="bold", command=make_bold)
aButton.grid()

aText.tag_config("bt", font=("Georgia", "12", "bold"))

lord.mainloop()

我刚刚偶然发现了一个很有教育意义的示例,正是 Bryan Oakley,
在完全不相关的搜索中!

I just happened across a rather educational example by none other than Bryan Oakley,
on a completely unrelated search!

以下是更动态的替代方案的快速示例:

Here is a quick example of the more dynamic alternative:

import Tkinter as tk
import tkFont

def make_bold():
    current_tags = aText.tag_names("sel.first")
    if "bt" in current_tags:
        aText.tag_remove("bt", "sel.first", "sel.last")
    else:
        aText.tag_add("bt", "sel.first", "sel.last")


lord = tk.Tk()

aText = tk.Text(lord, font=("Georgia", "12"))
aText.grid()

aButton = tk.Button(lord, text="bold", command=make_bold)
aButton.grid()

bold_font = tkFont.Font(aText, aText.cget("font"))
bold_font.configure(weight="bold")
aText.tag_configure("bt", font=bold_font)

lord.mainloop()

这篇关于设置为使用标签加粗所选文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆