Python find function selects one match per line
I am trying to make a simple text editor using python. I am now trying to make a find function. This is what I've got:
def Find(): text = textArea.get('1.0', END+'-1c').lower() input = simpledialog.askstring("Find", "Enter text to find...").lower() startindex =  endindex =  lines = 0 if input in text: text = textArea.get('1.0', END+'-1c').lower().splitlines() for var in text: character = text[lines].index(input) start = str(lines + 1) + '.' + str(character) startindex.append(start) end = str(lines + 1) + '.' + str(character + int(len(input))) endindex.append(end) textArea.tag_add('select', startindex[lines], endindex[lines]) lines += 1 textArea.tag_config('select', background = 'green')
This will succesfully highlight words that match the users input with a green background. But the problem is, that it only highlights the first match every line, as you can see here.
I want it to highlight all matches.
Full code here: https://pastebin.com/BkuXN5pk
Recommend using the text widget's built-in search capability. Shown using python3.
from tkinter import * root = Tk() textArea = Text(root) textArea.grid() textArea.tag_config('select', background = 'green') f = open('mouse.py', 'r') content = f.read() f.close() textArea.insert(END, content) def Find(input): start = 1.0 length = len(input) while 1: pos = textArea.search(input, start, END) if not pos: break end_tag = pos + '+' + str(length) + 'c' textArea.tag_add('select', pos, end_tag) start = pos + '+1c' Find('display') root.mainloop()
See also questions close to this topic
How do I re-use trained fastai models?
How do I load pretrained model using fastai implementation over PyTorch? Like in SkLearn I can use pickle to dump a model in file then load and use later. I've use .load() method after declaring learn instance like bellow to load previously saved weights:
arch=resnet34 data = ImageClassifierData.from_paths(PATH, tfms=tfms_from_model(arch, sz)) learn = ConvLearner.pretrained(arch, data, precompute=False) learn.load('resnet34_test')
Then to predict the class of an image:
trn_tfms, val_tfms = tfms_from_model(arch,100) img = open_image('circle/14.png') im = val_tfms(img) preds = learn.predict_array(im[None]) print(np.argmax(preds))
But It gets me the error:
ValueError: Expected more than 1 value per channel when training, got input size [1, 1024]
This code works if I use
learn.fit(0.01, 3)instead of
learn.load(). What I really want is to avoid the training step In my application.
How to disable/enable the ctrl+alt+delete combinations key using pyhook?
I have referred this link and disabled some of the combination keys but I am unable to disable ctrl+alt+del. Please let me know if it is possible to disable using pyhook or any other alternative solution using python code.
Call methods in list except for methods specified
I have a list of methods and I can call all of the methods at once with another method.
How can I call the method which contains all while leaving out certain items(or methods) from the list? I can currently specify one to leave out. I am not sure how to leave out more than one. Here is what I am working with:
class SomeClass: def method_a(self): print('method_a') def method_b(self): print('method_b') def method_c(self): print('method_c') def method_runner(self, skip_name='' ): for m in [self.method_a, self.method_b, self.method_c]: if m.__name__ != skip_name: m()
Now I can do this:
>>> some_obj = SomeClass() >>> some_obj.method_runner('') method_a method_b method_c >>> some_obj.method_runner('method_a') method_b method_c >>> some_obj.method_runner('method_b') method_a method_c
Is there a way to do something like this?
class SomeClass: def method_a(self): print('method_a') def method_b(self): print('method_b') def method_c(self): print('method_c') def method_runner(self, skip_name='', skip_name2='', skip_name3=''): for m in [self.method_a, self.method_b, self.method_c]: options = [skip_name, skip_name2, skip_name3] for o in options: if m.__name__ != o: m()
And specify more than one method to get an outcome such as:
>>> some_obj.method_runner('method_a', 'method_c') method_b
Rotate overlaid transparent image on another transparent image in Python 3.6 and Tkinter
I'm working on a simple raspberry pi digital dashboard for a car and i have chosen Python 3.6 as my programming language, and Tkinter as the main GUI library - i am relatively new to both of them.
import tkinter as tk from PIL import Image, ImageTk root = tk.Tk() def currentData(): print("pretend to get values from car") return 99 def my_mainloop(): # get data from car currentValues = currentData() #do more stuff i suppose root.after(my_mainloop) homeFrame = tk.Frame(root, height="600", width="800", bg="black") homeFrame.grid(row=0, column=0) dial_1_path = "gauge1.png" needle_1_path = "needle2.png" '''Open image (GUAGE1) and resize it to proper length''' img = Image.open(dial_1_path, 'r') #open image img2 = img.resize((400, 288), 1) img2 = ImageTk.PhotoImage(img2) '''put image on label and display it on homeFrame''' image_panel = tk.Label(homeFrame, image=img2, bg="black") image_panel.grid(row=0, column=0) '''----------------------------------------------------------------------------------------''' '''Open image (NEEDLE1) and resize it to proper length''' img_needle = Image.open(needle_1_path, 'r') #open image img2_needle = img_needle.resize((200, 17), 1) img2_needle = ImageTk.PhotoImage(img2_needle) #put image on label and dispaly it on homeFrame image_panel2 = tk.Label(homeFrame, image=img2_needle) image_panel2.grid(row=0, column=0) #does not produce desired effect! root.after(100, my_mainloop) root.mainloop()
The way i currently structure the layers of my window is as follows:
- The very bottom layer is the
rootwith a standard background
homeFrameframe is layered above that with a black background
- then a label containing the image of the transparent-background speed gauge is overlaid ontop
homeFramewith a black background
- then finally a label containing the image of the transparent-background gauge needle is overlaid ontop of the gauge in
homeFrameby using grid coordinates
I realize that labels do not support transparency, so:
Q1: are there any containers that support images and transparent backgrounds?
What i simply want is to have the gauge and needle image be two separate objects which can be controlled independently from one another. I need the needle to be able to rotate over the dial but have its transparency work.
What i could do is have the two objects separate in code and rotate the needle individually then merge the images together HOWEVER i need this application to run at 1080p 60Hz on a monitor therefore
Q2: is the merge method i described above an efficient way of creating the effect of a transparency working speed gauge? Multiple gauges need to run on a raspberry pi 3 model B (Quad Core 1.2GHz Broadcom BCM2837 64bit CPU on 1080p 60Hz monitor)
Q3: is Tkinter even the right library for the task? require something that i can program in python. Any other good choice?
I realize that i'm a little all over the place, but im really just trying to wrap my brain around this so any help and guidance at all is greatly appreciated!
- The very bottom layer is the
tkinter grid overlapping
I am building a calendar that allows the user to cycle through the months and years by pressing the buttons created of the previous month and next month. Below is the part where I am having issues:
def prevMonth(self): try: self.grid_forget() #SHOULD REFRESH THE WINDOW SO BUTTONS DONT OVERLAP print "forgeting" except: print "passed the forgetting" pass lastMonth = self.month - 1 self.month = lastMonth self.curr_month() def nextMonth(self): try: self.grid_forget() #SHOULD REFRESH THE WINDOW SO BUTTONS DONT OVERLAP print "forgeting" except: print "passed the forgetting" pass nextMonth = self.month + 1 self.month = nextMonth self.curr_month()
When the program iterates between the months the grid does not refresh it just overlaps the days and months. I have tried EVERYTHING I found in my hours of research. "self.destroy()" merely creates a blank window. "self.grid.destroy()" returns and error that function has no attribute destroy. I have tried making the children of grid all global variables within self and I cant iterate through the months correctly so the set up is permanent but I feel like I am missing something simple as far as working with refreshing the grid and reprinting the based upon the updated month.
Can you please point me in the right direction or correct the error I am missing?
below is the entire program
from Tkinter import * from calendar import * import datetime class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.grid() DateNow = datetime.datetime.now() self.year = DateNow.year#declaring global variable year self.month = DateNow.month#declaring global variable month self.curr_month() def curr_month(self): try:#iterating the month and year backward if index is out of range if self.month == 0: self.month = 12 trueYear = int(self.year) self.year = trueYear - 1 except: pass try:#iterating month and year forward if index is out of range if self.month == 13: self.month = 1 trueYear = int(self.year) self.year = trueYear + 1 except: pass days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] #create labels self.label = Label(self, text=months[self.month - 1])#displaying month self.label.grid(row=0, column = 1) self.label = Label(self, text=self.year)#displaying year self.label.grid(row=0, column = 6) try:#displaying previous month prevMonthBut = Button(self, text=months[self.month-2], command=self.prevMonth) prevMonthBut.grid(row=0,column=0) except:#USED ONLY IF PREVIOUS MONTH IS IN PREVIOUS YEAR prevMonthBut = Button(self, text=months, command=self.prevMonth) prevMonthBut.grid(row=0,column=0) try:#displaying next month nextMonthBut = Button(self, text=months[self.month], command=self.nextMonth) nextMonthBut.grid(row=0,column=2) except:#USED ONLY IF NEXT MONTH IS IN NEXT YEAR nextMonthBut = Button(self, text=months, command=self.nextMonth) nextMonthBut.grid(row=0,column=2) for i in range(7): self.label = Label(self, text=days[i]) self.label.grid(row = 1, column = i) weekday, numDays = monthrange(self.year, self.month) week = 2 for i in range(1, numDays + 1): self.button = Button(self, text = str(i)) self.button.grid(row = week, column = weekday) weekday += 1 if weekday > 6: week += 1 weekday = 0 def prevMonth(self): try: self.grid_forget() #SHOULD REFRESH THE WINDOW SO BUTTONS DONT OVERLAP print "forgeting" except: print "passed the forgetting" pass lastMonth = self.month - 1 self.month = lastMonth self.curr_month() def nextMonth(self): try: self.grid_forget() #SHOULD REFRESH THE WINDOW SO BUTTONS DONT OVERLAP print "forgeting" except: print "passed the forgetting" pass nextMonth = self.month + 1 self.month = nextMonth self.curr_month() mainWindow = Tk() obj = Application() mainWindow.mainloop()here
How can I draw a polka dot target using tkinter python with different colours? Picture in body
I'm always getting stuck over lapping my the colours. Picture
Here's an example of what I do:
from random import * from tkinter import * from math import * myInterface = Tk() s = Canvas(myInterface, width=600, height=600, background="white") s.pack() s.update() u = 50 color = ["red","blue","green","black"] for n in range(7000): x1 = randint(0,600) y1 = randint(0,600) x2 = x1 + 4 y2 = y1 + 4 s.create_oval(x1,y1,x2,y2, fill = color) s.create_oval(0,0,600,600, fill = "white", outline = "white") for n in range(3500): x1= randint(100,500) y1= randint(100,500) x2 = x1 + 4 y2 = y1 + 4 s.create_oval(x1,y1,x2,y2, fill = color, outline = color) s.create_oval(50,50,550,550, outline = "white", width = 105) #s.create_oval(200,200,400,400, width = 100, outline = "white") for n in range(1500): x1= randint(200,400) y1= randint(200,400) x2 = x1 + 4 y2 = y1 + 4 s.create_oval(x1,y1,x2,y2, fill = color, outline = color) #s.create_oval(150,150,450,450, width = 100, outline = "white")
The colors overlap and adding layers just doesn't work because it would put two colors in the same circle radius.
How to work with PHP, HTML, CSS & JS in same file simultaneously using eclipse for php
Please tell me how to work with PHP, HTML, CSS & JS within same file simultaneously. I mean I do this most often, that the file is
*.phpextension but I have to write HTML, CSS, PHP, JS all in the same file.
So that for each language code hinting could work, it doesn't work.
I have already download
- Eclipse for PHP
but both run separately. How can I combine? Please help.
Explicitly say which conditions to fold Notepad++
I have a custom language for SQR and I'm trying to get the code folding feature to work for Notepad++. In SQR, the case of the keywords do not matter.
Begin-Procedureis the same as
bEgIn-ProCEdure. The same goes for the traditional
if ... end-ifis the same as
If ... End-If.
In notepad++ you can specify a code folding feature to fold the code. My problem is that I only want to specify the code to fold on
if ... end-ifregardless of case. Notepad++ currently tries to fold code everywhere it sees
Meaning, if I name a procedure with
Begin-Procedure Verify-Something, the
ifin verify attempts to get folded leaving me with undesirable results.
How can I specifically specify I only want to fold code on the single instances of
ifand not wherever
Replacing comma by dot only in numbers in a texteditor using search and replace function
i got a table as txt.file with all the variables beeing seperated by ;.
Lets say i got 3 Variables: ID, Size and Comment.
My Data could look something like this:
1;1.5;hello. how are you? 2;2.5;a comment. 3;2.1;another comment.
Now i would like to replace the comma-sign from dot to comma.
If i use the standard search and replace function in my text-editor it will change all
,without any problem. But i want to change only those
,which are surrounded by numbers left side and right side.
1.5should be changed to
hello. how are you?should not be changed to
hello, how are you?
I found a regular expression for searching only dots surroundet by numbers:
Now i would like to replace those surroundet dots, but unfortunately it doesn't work yet. When replacing
1.5is changed to
,only instead of
Is there any nice way to use search and replace from a texteditor to solve this problem?
Thanks in advance!