how to highlight text in tkinter? , do you know what i am doing wrong ?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • moroccanplaya
    New Member
    • Jan 2011
    • 80

    how to highlight text in tkinter? , do you know what i am doing wrong ?

    hi i have text in a tkinter text widget, how would i highlight specific letters?

    Code:
      Text.tag_config("s", background="yellow")
      Text.insert(END,("s"))
    the code above just adds s to the end of the text, do you know what i am doing wrong ?
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    You are telling Tkinter to insert text "s" at the end. The following will highlight a sequence of characters:
    Code:
    ....snip....
            self.Btn1 = Tkinter.Button(self.mainFrame,
                                            text="Highlight 's'",
                                            command=lambda: self.highlight("s"))
            self.Btn1.grid(row=3, column=0, sticky="ns")
    
        def highlight(self, seq):
            if "highlight" in self.textWidget.tag_names():
                self.textWidget.tag_delete("highlight")
            i = len(seq)
            idx = "1.0"
            while True:
                idx = self.textWidget.search(seq, idx, nocase=1, stopindex='end')
                if idx:
                    idx2 = self.textWidget.index("%s+%dc" % (idx, i))
                    self.textWidget.tag_add("highlight", idx, idx2)
                    self.textWidget.tag_config("highlight", background="yellow")
                    idx = idx2
                else: return
    ....snip....
    Maybe there's a better way?

    Comment

    • moroccanplaya
      New Member
      • Jan 2011
      • 80

      #3
      is there any tutorial, or documentation on using tags and doing highlights in python 3 ?

      i have tried this but its not working
      Code:
      def highlight(seq):
          if "highlight" in Text.tag_names():
              Text.tag_delete("highlight")
       
              i = len(seq)
              index = "1.0"
              while True:
                  index = Text.search(seq, index, nocase=1, stopindex='end')
                  if index:
                      index2 = Text.index("%s+%d" % (index, i))
                      Text.tag_add("highlight", index, index2)
                      Text.tag_config("highlight", background="yellow")
                      index = index2
                  else: return

      Comment

      • moroccanplaya
        New Member
        • Jan 2011
        • 80

        #4
        as im trying to highlight white spaces, is there away of highlighting in a for loop, for example for " " in ttk.Text, highlight in yellow ??

        Comment

        • bvdet
          Recognized Expert Specialist
          • Oct 2006
          • 2851

          #5
          You can highlight any sequence of text, including a space character, with the code I posted.

          Comment

          • moroccanplaya
            New Member
            • Jan 2011
            • 80

            #6
            i tried to modify the code, but something went wrong it is not highlighting anything

            Code:
            def highlight(seq):
                
                if "highlight" in Text.tag_names():
                    Text.tag_delete("highlight")
            
                    i = len(seq)
                    index = "1.0"
                    while True:
                        index = Text.search(seq, index, nocase=1, stopindex='end')
                        if index:
                            index2 = Text.index("%s+%d" % (index, i))
                            Text.tag_add("highlight", index, index2)
                            Text.tag_config("highlight", background="yellow")
                            index = index2
                        else: return

            Comment

            • bvdet
              Recognized Expert Specialist
              • Oct 2006
              • 2851

              #7
              It's possible the ttk.Text widget doesn't work like a Tkinter.Text widget. Following is the complete code for a Tkinter Text widget with a button to highlight the text "bolt". It works in Python 2.7.2.
              Code:
              import Tkinter
              """
              Edit a file and save the text.
              """
              
              textFont1 = ("Courier New", 16, "normal")
              
              class ScrollbarX(Tkinter.Scrollbar):
                  def set(self, low, high):
                      if float(low) <= 0.0 and float(high) >= 1.0:
                          self.grid_remove()
                      else:
                          self.grid()
                      Tkinter.Scrollbar.set(self, low, high)
              
              class App(Tkinter.Tk):
                  def __init__(self, fn, fnout):
                      Tkinter.Tk.__init__(self)
                      self.title("Text Widget")
                      self.fin = open(fn, 'r')
                      self.fnout = fnout
                      self.mainFrame = Tkinter.Frame(self)
                      
                      top=self.winfo_toplevel()
                      top.columnconfigure(0, weight=1)
                      top.rowconfigure(0, weight=1)
                      
                      self.mainFrame.grid(row=0, column=0, sticky="nsew")
                      self.exit = Tkinter.Button(self.mainFrame,
                                                 text="Save and Exit",
                                                 command=self.finish)
                      self.exit.grid(row=0, column=0, sticky="ns")
              
              
                      self.mainFrame.columnconfigure(0, weight=1)
                      self.mainFrame.rowconfigure(1, weight=1)
                      
                      vscrollbar = ScrollbarX(self.mainFrame)
                      vscrollbar.grid(row=1, column=1, sticky="ns")
                      hscrollbar = ScrollbarX(self.mainFrame, orient=Tkinter.HORIZONTAL)
                      hscrollbar.grid(row=2, column=0, sticky="ew")
                      
                      self.textWidget = Tkinter.Text(self.mainFrame,
                                                     yscrollcommand=vscrollbar.set,
                                                     xscrollcommand=hscrollbar.set,
                                                     wrap=Tkinter.NONE,
                                                     height=24,
                                                     width=60,
                                                     font=textFont1)
                      self.textWidget.insert("1.0", self.fin.read())
                      self.textWidget.grid(row=1, column=0, sticky="nsew")
              
                      hscrollbar["command"] = self.textWidget.xview
                      vscrollbar["command"] = self.textWidget.yview
              
                      self.Btn1 = Tkinter.Button(self.mainFrame,
                                                      text="Highlight 'bolt'",
                                                      command=lambda: self.highlight("bolt"))
                      self.Btn1.grid(row=3, column=0, sticky="ns")
                      
                  def finish(self):
                      fout = open(self.fnout, 'w')
                      fout.write(self.textWidget.get("1.0", "end"))
                      fout.close()
                      self.fin.close()
                      app.destroy()
              
                  def highlight(self, seq):
                      if "highlight" in self.textWidget.tag_names():
                          self.textWidget.tag_delete("highlight")
                      i = len(seq)
                      idx = "1.0"
                      while True:
                          idx = self.textWidget.search(seq, idx, nocase=1, stopindex='end')
                          if idx:
                              idx2 = self.textWidget.index("%s+%dc" % (idx, i))
                              self.textWidget.tag_add("highlight", idx, idx2)
                              self.textWidget.tag_config("highlight", background="yellow")
                              idx = idx2
                          else: return
              
              if __name__ == "__main__":
                  fn = "text1.txt"
                  fnout = "text2.txt"
                  app = App(fn, fnout)
                  app.mainloop()

              Comment

              • moroccanplaya
                New Member
                • Jan 2011
                • 80

                #8
                im using tkinter.Text widget ?, im confused, so the example wont work in python 3

                Comment

                • bvdet
                  Recognized Expert Specialist
                  • Oct 2006
                  • 2851

                  #9
                  Since I don't have Python 3 installed, there is no way for me to test it. I believe it can easily be converted though. Replace every occurrence of "Tkinter" with "tkinter". That should take care of most if not all of it.

                  Comment

                  • moroccanplaya
                    New Member
                    • Jan 2011
                    • 80

                    #10
                    yeah i replaced it and the program does work in python 3, i'm struggling to understand how the highlighting is done in that program, still cant get the highlighting to work in my program

                    Comment

                    • bvdet
                      Recognized Expert Specialist
                      • Oct 2006
                      • 2851

                      #11
                      Function highlight() basically works like this:
                      1. If the Text widget has a tag named "highlight" , delete all occurrences
                      2. Save the length of the text string "seq"
                      3. Set the starting index of the widget to "1.0"
                      4. Start a loop
                      5. Use Text widget method "search" to find the next occurrence of "seq"
                      6. If no occurrence of "seq", return
                      7. If there is an occurrence, calculate the next index from the old index and the length of "seq"
                      8. Add a tag named "highlight" from idx to idx2
                      9. Configure the tag "yellow"
                      10. Reassign idx to idx2

                      Comment

                      • moroccanplaya
                        New Member
                        • Jan 2011
                        • 80

                        #12
                        so basically i think the highlight function is not working with my button

                        Comment

                        • moroccanplaya
                          New Member
                          • Jan 2011
                          • 80

                          #13
                          Code:
                          button4 = ttk.Button(content,text="highlight", command=lambda: highlight(" "))

                          Comment

                          • bvdet
                            Recognized Expert Specialist
                            • Oct 2006
                            • 2851

                            #14
                            moroccanplaya - That should work. If it doesn't, there is something else wrong.

                            Comment

                            • moroccanplaya
                              New Member
                              • Jan 2011
                              • 80

                              #15
                              i have used the same highlight function as in the example you gave me i just removed the self and tried using both tkinter.text and textWidget to see if they work, i used

                              Code:
                              if "highlight" in tkinter.Text.tag_names():
                              and i revived an error stating that tag_names takes at least 1 argument

                              then i changed it back just to :

                              Code:
                               if "highlight" in Text.tag_names():
                              i get no error

                              Comment

                              Working...