Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6667013
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T02:53:19+00:00 2026-05-26T02:53:19+00:00

I need some help tag-related! I am writing a simple editor, supporting basic formatting.

  • 0

I need some help tag-related!

I am writing a simple editor, supporting basic formatting.
By using a Text widget (named text), I put a tag ‘b’ to set the text where this tag applies to bold.

This is not a problem when I apply the bold to a selection:

text.tag_add('b', SEL_FIRST,SEL_LAST)

I have instead two problems when I just want to switch on/off the bold while typing.
To switch it on the only way I found is this:

text.insert(INSERT, '  ', 'b' )
text.mark_set("insert", INSERT+'-1c')

notice that I have to insert TWO spaces. If I insert one, the bold doesnt apply. If I insert ”, my cursor goes back one char!

My second problem is how to switch it off, when I’m writing within a bolded region – and for this I havent the slightest idea…

Thanks for any help!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T02:53:20+00:00Added an answer on May 26, 2026 at 2:53 am

    You may not realize it, but you’re trying to do something that’s very hard in Tkinter. While the text widget tags are a powerful concept, they have some weaknesses when it comes to creating something like a wysywig editor.

    You need to change your approach a bit. Instead of inserting spaces, I think the better solution is to add bindings that apply (or remove) your tags each time a character is inserted. This has it’s own set of problems, but with enough attention to detail you can overcome them. We can do that though a custom key binding.

    When you insert a character into a text widget, this is handled by a binding on the <Key> event on the text widget class. So, we could bind to <Key> to add the tag. However, if we add a binding to <Key> on the widget, this will fire before the class binding, meaning our code will execute before the character inserted rather than after. We’ll be trying to modify something that hasn’t actually been inserted into the widget yet.

    One way to solve that is to bind to a key release rather than a key press, since the character is inserted on the press. However, think of the scenario where a user presses and holds a key down — multiple characters will be entered but you may only get a single key-up event. So this solution isn’t particularly good.

    Another solution is to somehow arrange for our custom binding to happen after the default binding. To do that we need to do two things: 1) adjust the “bind tags” for the widget to have an additional tag after the class tag, and 2) add a binding to this new bind tag.

    There are downsides to this approach too. Not because of the bind tags, but because there are a lot more events you need to handle besides <Key> (for example, control-v to paste isn’t handled by the <Key> binding, so you’ll have to add a special case for pasting).

    That being said, this solution might be good enough for you, or at least good enough to help you better understand the problem, and understanding the problem is often the biggest obstacle to finding a solution.

    In the following example I have a text widget that has an additional bindtag named “CustomText” that we place after the standard “Text” bind tag. I put a binding on this tag for the <Key> event, and in the handler I simply apply the appropriate tags to the just-inserted character.

    You’ll have to add your own code to handle a clipboard paste, and the problem of dealing with conflicting tags (such as two tags each with their own font). Hopefully, though, this example will act as inspiration

    import Tkinter as tk
    
    class SampleApp(tk.Tk):
        def __init__(self, *args, **kwargs):
            tk.Tk.__init__(self, *args, **kwargs)
            self.tag_vars = {
                "underline": tk.IntVar(),
                "red": tk.IntVar(),
                }
    
            self.text = MyText(self, width=40, height=8)
            self.text.tag_configure("red", foreground="red")
            self.text.tag_configure("underline", underline=True)
    
            toolbar = tk.Frame(self)
            self.underline = tk.Checkbutton(self, text="Underline", 
                                            onvalue = True, offvalue=False,
                                            variable = self.tag_vars["underline"]
                                            )
            self.red = tk.Checkbutton(self, text="Red", 
                                      onvalue = True, offvalue=False,
                                      variable = self.tag_vars["red"]
                                      )
            self.underline.pack(in_=toolbar, side="left")
            self.red.pack(in_=toolbar, side="left")
    
            toolbar.pack(side="top", fill="x")
            self.text.pack(side="top", fill="both", expand=True)
    
    class MyText(tk.Text):
        def __init__(self, parent, *args, **kwargs):
            tk.Text.__init__(self, *args, **kwargs)
    
            self.parent = parent
    
            # add a new bind tag, "CustomText" so we
            # can have code run after the class binding
            # has done it's work
            bindtags = list(self.bindtags())
            i = bindtags.index("Text")
            bindtags.insert(i+1, "CustomText")
            self.bindtags(tuple(bindtags))
    
            # set a binding that will fire whenever a 
            # self-inserting key is pressed
            self.bind_class("CustomText", "<Key>", self.OnKey)
    
        def OnKey(self, event):
            # we are assuming this is called whenever 
            # a character is inserted. Apply or remove
            # each tag depending on the state of the checkbutton
            for tag in self.parent.tag_vars.keys():
                use_tag = self.parent.tag_vars[tag].get()
                if use_tag:
                    self.tag_add(tag, "insert-1c", "insert")
                else:
                    self.tag_remove(tag, "insert-1c", "insert")
    
    if __name__ == "__main__":
        app = SampleApp()
        app.mainloop()
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need some help to put a simple php tag in this code $return.=<form
I'm currently using json-framework and need some help though parsing some JSON i'm getting
I need some help on the xslt that I'm writing. Below is my source
I need some help in converting my script from using mysql to mysqli I
I need some help editing a csproj file using PowerShell. I basically need to
hi guys i need some help here^^ i got a tag <html> <head> function
I need some help or information with showing the image int the <img> tag
Need some help about with Memcache. I have created a class and want to
Need some help, please. I have a line of horizontal thumbnails loaded as ONE
Need some help to solve this. I have a gridview and inside the gridview

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.