473,473 Members | 1,816 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

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

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

Expand|Select|Wrap|Line Numbers
  1.  
  2.   Text.tag_config("s", background="yellow")
  3.   Text.insert(END,("s"))
  4.  
  5.  
  6.  
the code above just adds s to the end of the text, do you know what i am doing wrong ?
Feb 19 '12 #1
14 14384
bvdet
2,851 Recognized Expert Moderator Specialist
You are telling Tkinter to insert text "s" at the end. The following will highlight a sequence of characters:
Expand|Select|Wrap|Line Numbers
  1. ....snip....
  2.         self.Btn1 = Tkinter.Button(self.mainFrame,
  3.                                         text="Highlight 's'",
  4.                                         command=lambda: self.highlight("s"))
  5.         self.Btn1.grid(row=3, column=0, sticky="ns")
  6.  
  7.     def highlight(self, seq):
  8.         if "highlight" in self.textWidget.tag_names():
  9.             self.textWidget.tag_delete("highlight")
  10.         i = len(seq)
  11.         idx = "1.0"
  12.         while True:
  13.             idx = self.textWidget.search(seq, idx, nocase=1, stopindex='end')
  14.             if idx:
  15.                 idx2 = self.textWidget.index("%s+%dc" % (idx, i))
  16.                 self.textWidget.tag_add("highlight", idx, idx2)
  17.                 self.textWidget.tag_config("highlight", background="yellow")
  18.                 idx = idx2
  19.             else: return
  20. ....snip....
Maybe there's a better way?
Feb 20 '12 #2
moroccanplaya
80 New Member
is there any tutorial, or documentation on using tags and doing highlights in python 3 ?

i have tried this but its not working
Expand|Select|Wrap|Line Numbers
  1. def highlight(seq):
  2.     if "highlight" in Text.tag_names():
  3.         Text.tag_delete("highlight")
  4.  
  5.         i = len(seq)
  6.         index = "1.0"
  7.         while True:
  8.             index = Text.search(seq, index, nocase=1, stopindex='end')
  9.             if index:
  10.                 index2 = Text.index("%s+%d" % (index, i))
  11.                 Text.tag_add("highlight", index, index2)
  12.                 Text.tag_config("highlight", background="yellow")
  13.                 index = index2
  14.             else: return
  15.  
Feb 28 '12 #3
moroccanplaya
80 New Member
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 ??
Feb 28 '12 #4
bvdet
2,851 Recognized Expert Moderator Specialist
You can highlight any sequence of text, including a space character, with the code I posted.
Feb 28 '12 #5
moroccanplaya
80 New Member
i tried to modify the code, but something went wrong it is not highlighting anything

Expand|Select|Wrap|Line Numbers
  1. def highlight(seq):
  2.  
  3.     if "highlight" in Text.tag_names():
  4.         Text.tag_delete("highlight")
  5.  
  6.         i = len(seq)
  7.         index = "1.0"
  8.         while True:
  9.             index = Text.search(seq, index, nocase=1, stopindex='end')
  10.             if index:
  11.                 index2 = Text.index("%s+%d" % (index, i))
  12.                 Text.tag_add("highlight", index, index2)
  13.                 Text.tag_config("highlight", background="yellow")
  14.                 index = index2
  15.             else: return 
  16.  
  17.  
  18.  
Feb 29 '12 #6
bvdet
2,851 Recognized Expert Moderator Specialist
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.
Expand|Select|Wrap|Line Numbers
  1. import Tkinter
  2. """
  3. Edit a file and save the text.
  4. """
  5.  
  6. textFont1 = ("Courier New", 16, "normal")
  7.  
  8. class ScrollbarX(Tkinter.Scrollbar):
  9.     def set(self, low, high):
  10.         if float(low) <= 0.0 and float(high) >= 1.0:
  11.             self.grid_remove()
  12.         else:
  13.             self.grid()
  14.         Tkinter.Scrollbar.set(self, low, high)
  15.  
  16. class App(Tkinter.Tk):
  17.     def __init__(self, fn, fnout):
  18.         Tkinter.Tk.__init__(self)
  19.         self.title("Text Widget")
  20.         self.fin = open(fn, 'r')
  21.         self.fnout = fnout
  22.         self.mainFrame = Tkinter.Frame(self)
  23.  
  24.         top=self.winfo_toplevel()
  25.         top.columnconfigure(0, weight=1)
  26.         top.rowconfigure(0, weight=1)
  27.  
  28.         self.mainFrame.grid(row=0, column=0, sticky="nsew")
  29.         self.exit = Tkinter.Button(self.mainFrame,
  30.                                    text="Save and Exit",
  31.                                    command=self.finish)
  32.         self.exit.grid(row=0, column=0, sticky="ns")
  33.  
  34.  
  35.         self.mainFrame.columnconfigure(0, weight=1)
  36.         self.mainFrame.rowconfigure(1, weight=1)
  37.  
  38.         vscrollbar = ScrollbarX(self.mainFrame)
  39.         vscrollbar.grid(row=1, column=1, sticky="ns")
  40.         hscrollbar = ScrollbarX(self.mainFrame, orient=Tkinter.HORIZONTAL)
  41.         hscrollbar.grid(row=2, column=0, sticky="ew")
  42.  
  43.         self.textWidget = Tkinter.Text(self.mainFrame,
  44.                                        yscrollcommand=vscrollbar.set,
  45.                                        xscrollcommand=hscrollbar.set,
  46.                                        wrap=Tkinter.NONE,
  47.                                        height=24,
  48.                                        width=60,
  49.                                        font=textFont1)
  50.         self.textWidget.insert("1.0", self.fin.read())
  51.         self.textWidget.grid(row=1, column=0, sticky="nsew")
  52.  
  53.         hscrollbar["command"] = self.textWidget.xview
  54.         vscrollbar["command"] = self.textWidget.yview
  55.  
  56.         self.Btn1 = Tkinter.Button(self.mainFrame,
  57.                                         text="Highlight 'bolt'",
  58.                                         command=lambda: self.highlight("bolt"))
  59.         self.Btn1.grid(row=3, column=0, sticky="ns")
  60.  
  61.     def finish(self):
  62.         fout = open(self.fnout, 'w')
  63.         fout.write(self.textWidget.get("1.0", "end"))
  64.         fout.close()
  65.         self.fin.close()
  66.         app.destroy()
  67.  
  68.     def highlight(self, seq):
  69.         if "highlight" in self.textWidget.tag_names():
  70.             self.textWidget.tag_delete("highlight")
  71.         i = len(seq)
  72.         idx = "1.0"
  73.         while True:
  74.             idx = self.textWidget.search(seq, idx, nocase=1, stopindex='end')
  75.             if idx:
  76.                 idx2 = self.textWidget.index("%s+%dc" % (idx, i))
  77.                 self.textWidget.tag_add("highlight", idx, idx2)
  78.                 self.textWidget.tag_config("highlight", background="yellow")
  79.                 idx = idx2
  80.             else: return
  81.  
  82. if __name__ == "__main__":
  83.     fn = "text1.txt"
  84.     fnout = "text2.txt"
  85.     app = App(fn, fnout)
  86.     app.mainloop()
Feb 29 '12 #7
moroccanplaya
80 New Member
im using tkinter.Text widget ?, im confused, so the example wont work in python 3
Feb 29 '12 #8
bvdet
2,851 Recognized Expert Moderator Specialist
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.
Feb 29 '12 #9
moroccanplaya
80 New Member
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
Feb 29 '12 #10
bvdet
2,851 Recognized Expert Moderator Specialist
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
Feb 29 '12 #11
moroccanplaya
80 New Member
so basically i think the highlight function is not working with my button
Feb 29 '12 #12
moroccanplaya
80 New Member
Expand|Select|Wrap|Line Numbers
  1. button4 = ttk.Button(content,text="highlight", command=lambda: highlight(" "))
Mar 1 '12 #13
bvdet
2,851 Recognized Expert Moderator Specialist
moroccanplaya - That should work. If it doesn't, there is something else wrong.
Mar 1 '12 #14
moroccanplaya
80 New Member
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

Expand|Select|Wrap|Line Numbers
  1. 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 :

Expand|Select|Wrap|Line Numbers
  1.  if "highlight" in Text.tag_names():
i get no error
Mar 1 '12 #15

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Cox | last post by:
How would I go about highlighting text in a textbox?
2
by: parm | last post by:
How do I highlight text in my first (tabindex = 1) asp control (eg: textbox) on the webform on page load. If I try to set focus using javascript then I get script error "Cannot move focus to...
0
by: abc my vclass | last post by:
which properties to focus automatic highlight text on text when on fous?
5
by: ken | last post by:
Hi, I have two questions the first is: in the example below how can I call an event from within a statement, such as replace Stop1 with cmdStop1 which is a button on my form? My second question...
7
by: Sunil Korah | last post by:
Hi, I haven't used access reports much. I have a problem in getting the total of a group. I have 3 fields, ProgName (Program name), Pname (Participant's name) and PCategory (Participant...
2
by: shapper | last post by:
Hello, I have an ASP.NET page and in its runtime code I am trying to get an user profile, change it and save it. It works if I use Profile, which is the profile for the current authenticated...
8
by: watkinsdev | last post by:
Hi, I have created a mesh class in visual studio 6.0 c++. I can create a device, render objects and can edit the objects by for instancnce selecting a cluster of vertices and processing the...
8
by: =?Utf-8?B?Tmlja28u?= | last post by:
Hi, I'm at my wits-end here. I'm a beginner with ASP/C# (using .NET 2003) and I'm trying to post variables from a classic ASP form to a ASP.NET form. The Classic ASP form was scripted with...
5
by: Dave | last post by:
Is there a way to selectively highlight text in an OverLib popup? I'd like to be able to make some text stand out from the rest of the text that is displayed. I tried using a one-cell table with...
1
by: mbatestblrock | last post by:
I have no idea how to even phrase this.. I assume this is something easy. http://www.picment.com/articles/css/funwithforms/ just an example. When you highlight text with your mouse (as if you...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.