How can I select an item from a tkinter listbox? - python

The inp_list is a listbox. I wish to select the first item from that list. I tried to use inp_list.get(0) and alsoinp_list.select_set(0) but I get this error: _tkinter.TclError: invalid command name ".!listbox".
How can I choose it? (the problematic line is marked with ***)
def add_inp_func(inp_list):
inp_file = filedialog.askopenfile(mode='r', filetypes=[("Input files", '*.inp')])
if inp_file is not None:
inp_list.insert(END, utils.getFileNameWithoutBackSlash(inp_file.name))
def save_inp_func(inp_list,add_inp_window,table_frame):
#first_one = 0
for j in enumerate(inp_dict):
# if first_one == 0:
# first_one=1
# continue
del inp_dict[j]
i =1
for listbox_entry in inp_list.get(0, END):
inp_dict[i] =listbox_entry
i+=1
add_inp_window.destroy()
if inp_list:
erase_widgets()
inp_file = inp_dict[1]
if inp_file is not None: # in case someone presses the browse and doesnt choose anything
***working_dir = utils.getFolderPath(inp_list.get(0) ) # get path to the working*** directory
slashed_work_dir = utils.convertBackSlash(working_dir) ```

Related

On_click event on a TwoLineIconListItem in kivy

I have an array of values . I have to show this list in a TwoLineIconListItem in kivy along with an image icon and with other information in a list view. When the user clicks on any of the list item, a popup should come (preferably a dialog) and I have to show the item text selected...Pls do help !!
I could write everything but it seems like I am unable to pass the value to the dialog from my TwoLineIconListItem...the code snippet is here where I need some help to achieve this please...
while counter < len(list_of_names):
self.party_name = list_of_names[counter]
self.party_pic = IconLeftWidget(icon=image_source + "\\" + list_of_names[counter].lower() + ".png")
counter += 1
items = TwoLineIconListItem(text=str(counter) + " : " + self.party_name,
secondary_text=self.party_name_details,
on_release=self.select_item)
items.add_widget(self.party_pic)
list_view.add_widget(items)
screen.add_widget(scroll)
return screen
def select_item(self, obj):
print(obj)
# It's should print the item text selected
close_btn = MDFlatButton(text="Close", on_release=self.close_dialog)
confirm_btn = MDFlatButton(text="I Confirm !", on_release=self.confirm_choice)
self.dialog = MDDialog(title="Please confirm your choice!",
text=self.party_name,
size_hint=(0.7, 1),
buttons=[close_btn, confirm_btn]
)
self.dialog.open()

How about use Face Recognition?

I am using Face Recognition. When I load a folder and choose an image of the person, after that the script will find all images associated with that person and delete them. But when I run the code it deletes all the pictures with faces.
CODE 1:
def load_file(self):
filename = askopenfilename()
self._file_field.delete(0, tk.END) # deletes the current value
self._file_field.insert(0, filename)
for widget in self._image_panel.winfo_children():
widget.destroy()
img = ImageTk.PhotoImage(Image.open(filename))
panel = tk.Label(self._image_panel, image=img)
panel.img = img
panel.pack(side="bottom", fill="both", expand="yes")
CODE 2:
def load_folder(self):
filename = askdirectory()
self._folder_field.delete(0, tk.END) # deletes the current value
self._folder_field.insert(0, filename)
CODE 3:
def start_process(self):
ref_path = self._file_field.get()
folder_path = self._folder_field.get()
self.find_and_delete(folder_path, ref_path)
CODE 4:
def run_process(self):
self._run_task = True
t = Thread(target=self.start_process)
t.start()
CODE 5:
def find_and_delete(self, directory, ref_image_path):
ref_face = self.get_ref_face(ref_image_path)
if ref_face is None:
messagebox.showinfo("Error", "Can't find a face. Reference Image quality is not enough")
return
files = os.listdir(directory)
i = 1
for filename in files:
try:
percentage = int((i / len(files)) * 100)
self._progress['value'] = percentage
self.update_idletasks()
i += 1
file_path = os.path.join(directory, filename)
if self.is_user_in_image(ref_face, file_path):
os.remove(file_path)
print(filename, 'deleted.')
except:
print('Error reading file', filename)
messagebox.showinfo("Information", "Process Finished")
CODE 6
def get_ref_face(self, ref_image_path):
try:
ref_image = face_recognition.load_image_file(ref_image_path)
ref_face = face_recognition.face_encodings(ref_image)[0]
return ref_face
except:
return None
CODE 7:
def is_user_in_image(self, ref_face, image_path):
unknown_picture = face_recognition.load_image_file(image_path)
unknown_faces = face_recognition.face_encodings(unknown_picture)
for unknown_face in unknown_faces:
results = face_recognition.compare_faces([ref_face], unknown_face)
if results[0]:
return True
return False
It's realy hard to understand what and when your code fragments are doing but it is possible that your CODE 7 recognizes everyone as similar enougth ones with default tolerance.
Try something like that
results = face_recognition.compare_faces([ref_face], unknown_face, tolerance=0.15)

tkinter invalid command name when inserting to text box

I have the following Notepad class and I need to insert a string to the textbox __thisLinkArea.
import tkinter
import os
from tkinter import *
from tkinter.messagebox import *
from tkinter.filedialog import *
class Notepad:
__root = Tk()
# default window width and height
__thisWidth = 300
__thisHeight = 300
__thisTextArea = Text(__root)
__thisLinkArea = Text(__root)
__thisMenuBar = Menu(__root)
__thisFileMenu = Menu(__thisMenuBar, tearoff=0)
__thisEditMenu = Menu(__thisMenuBar, tearoff=0)
__thisHelpMenu = Menu(__thisMenuBar, tearoff=0)
# To add scrollbar
__thisScrollBar = Scrollbar(__thisTextArea)
__file = None
def __init__(self,**kwargs):
# Set icon
try:
self.__root.wm_iconbitmap("Notepad.ico")
except:
pass
# Set window size (the default is 300x300)
try:
self.__thisWidth = kwargs['width']
except KeyError:
pass
try:
self.__thisHeight = kwargs['height']
except KeyError:
pass
# Set the window text
self.__root.title("Untitled - Notepad")
# Center the window
screenWidth = self.__root.winfo_screenwidth()
screenHeight = self.__root.winfo_screenheight()
# For left-align
left = (screenWidth / 2) - (self.__thisWidth /2)
# For right-align
top = (screenHeight / 2) - (self.__thisHeight /2 )
# For top and bottom
self.__root.geometry('%dx%d+%d+%d' % (self.__thisWidth,
self.__thisHeight,
left, top))
# To make the textarea auto resizable
self.__root.grid_rowconfigure(0, weight=1)
self.__root.grid_columnconfigure(0, weight=1)
# Add controls (widget)
self.__thisTextArea.grid(sticky = N + E + S + W)
self.__thisLinkArea.grid(column = 0, row = 2)
# To open new file
self.__thisFileMenu.add_command(label="New",
command=self.__newFile)
# To open a already existing file
self.__thisFileMenu.add_command(label="Open",
command=self.__openFile)
# To save current file
self.__thisFileMenu.add_command(label="Save",
command=self.__saveFile)
# To create a line in the dialog
self.__thisFileMenu.add_separator()
self.__thisFileMenu.add_command(label="Exit",
command=self.__quitApplication)
self.__thisMenuBar.add_cascade(label="File",
menu=self.__thisFileMenu)
# To give a feature of cut
self.__thisEditMenu.add_command(label="Cut",
command=self.__cut)
# to give a feature of copy
self.__thisEditMenu.add_command(label="Copy",
command=self.__copy)
# To give a feature of paste
self.__thisEditMenu.add_command(label="Paste",
command=self.__paste)
# To give a feature of editing
self.__thisMenuBar.add_cascade(label="Edit",
menu=self.__thisEditMenu)
# To create a feature of description of the notepad
self.__thisHelpMenu.add_command(label="About Notepad",
command=self.__showAbout)
self.__thisMenuBar.add_cascade(label="Help",
menu=self.__thisHelpMenu)
self.__root.config(menu=self.__thisMenuBar)
self.__thisScrollBar.pack(side=RIGHT,fill=Y)
# Scrollbar will adjust automatically according to the content
self.__thisScrollBar.config(command=self.__thisTextArea.yview)
self.__thisTextArea.config(yscrollcommand=self.__thisScrollBar.set)
def __quitApplication(self):
self.__root.destroy()
# exit()
def __showAbout(self):
showinfo("Notepad","Mrinal Verma")
def __openFile(self):
self.__file = askopenfilename(defaultextension=".txt",
filetypes=[("All Files","*.*"),
("Text Documents","*.txt")])
if self.__file == "":
# no file to open
self.__file = None
else:
# Try to open the file
# set the window title
self.__root.title(os.path.basename(self.__file) + " - Notepad")
self.__thisTextArea.delete(1.0,END)
file = open(self.__file,"r")
self.__thisTextArea.insert(1.0,file.read())
file.close()
def __newFile(self):
self.__root.title("Untitled - Notepad")
self.__file = None
self.__thisTextArea.delete(1.0,END)
def __saveFile(self):
if self.__file == None:
# Save as new file
self.__file = asksaveasfilename(initilfile='Untitled.txt',
defaultextension=".txt",
filetypes=[("All Files","*.*"),
("Text Documents","*.txt")])
if self.__file == "":
self.__file = None
else:
# Try to save the file
file = open(self.__file,"w")
file.write(self.__thisTextArea.get(1.0,END))
file.close()
# Change the window title
self.__root.title(os.path.basename(self.__file) + " - Notepad")
else:
file = open(self.__file,"w")
file.write(self.__thisTextArea.get(1.0,END))
file.close()
def __cut(self):
self.__thisTextArea.event_generate("<<Cut>>")
def __copy(self):
self.__thisTextArea.event_generate("<<Copy>>")
def __paste(self):
self.__thisTextArea.event_generate("<<Paste>>")
def append(self,a):
self.__thisLinkArea.insert('1.0',a)
def run(self):
# Run main application
self.__root.mainloop()
but it doesnt insert anything and when i quit the terminal gives the following output:
python3 ~/pp/ecoi.py
Traceback (most recent call last):
File "/home/josquin/pp/ecoi.py", line 13, in <module>
notepad.append('ciao')
File "/home/josquin/pp/editortry1.py", line 195, in append
self.__thisLinkArea.insert('1.0',a)
File "/usr/lib/python3.8/tkinter/__init__.py", line 3738, in insert
self.tk.call((self._w, 'insert', index, chars) + args)
_tkinter.TclError: invalid command name ".!text2"
In this specific case, as you can see, i'm importing Notepad and calling Notepad.append('string') from another script ecoi.py which is in the same path.

How to get index of a cell in QTableWidget?

I created a table widget and added a contextmenu to it. When I right click the cell,I want to get a file directory and put it into the cell. I've got the directory and pass it to a variable, but i failed to display it in the cell,because I can't get the index of the cell.How to get index of a cell in QTableWidget? Is there any orther method to figure out this qusstion? I'm using Python and PyQt5.
enter image description here
#pyqtSlot()
def on_actionAddFolder_triggered(self):
# TODO: Open filedialog and get directory
filedir = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
return filedir
#pyqtSlot(QPoint)
def on_tableWidget_customContextMenuRequested(self, pos):
# TODO: get directory and display it in the cell
x = self.tableWidget.currentRow
y = self.tableWidget.currentColumn
RightClickMenu = QMenu()
AddFolder = RightClickMenu.addAction('Add Folder')
FolderAction = RightClickMenu.exec_(self.tableWidget.mapToGlobal(pos))
if FolderAction == AddFolder:
NewItem = QTableWidgetItem(self.on_actionAddFolder_triggered())
self.tableWidget.setItem(x,y, NewItem)
hahaha, I find the mistake!
x = self.tableWidget.currentRow
y = self.tableWidget.currentColumn
replace these two lines
x = self.tableWidget.currentRow()
y = self.tableWidget.currentColumn()
then it works.

Python 3.3 Can't change Tkinter Label text attribute

I keep on getting an attribute error when trying to changing the text attribute of a tk label.
I declare it and it uses a temp image so it does exist but when I attempt to change it I get the error. If someone knows a better way to change the image or display it in a better method I would greatly like to here.
Here is the relevent code
self.threadLabelImage = tk.Label(self.threadFrame,image=self.threadImage,wraplength=400,padx=20,pady=5).grid(row=7,column=10,sticky = tk.EW)
self.threadFrame.grid(row=0,column=10,sticky=tk.EW,rowspan=8)
self.threadFrame.grid_propagate(0)
self.QUIT = tk.Button(self, text="QUIT", fg="red", command=main.destroy,padx=5, pady=5).grid(row=7)
def updateSelected(self, event):
# getting selected listbox item
i=self.thread_lb.curselection()
# Returns tuple that must be split
x,self.y,z = re.split("\D+",str(i))
self.y=int(self.y)
print(self.threadTitleList[self.y])
print(self.threadPubDateList[self.y])
print(self.threadLinkList[self.y])
print(self.threadDescList[self.y])
self.threadTitle.set(self.threadTitleList[self.y])
self.threadAuth.set(self.threadAuthList[self.y])
self.threadPub.set(self.threadPubDateList[self.y])
self.threadArtLink.set(self.threadLinkList[self.y])
self.threadLink.set(self.threadDescList[self.y])
self.threadImg.set('Will put image here')
if self.threadLinkList[self.y].find('imgur') != -1:
url = self.threadLinkList[self.y]+'.GIF'
imageName=self.threadLinkList[self.y][-11:-4]
urllib.request.urlretrieve(self.threadLinkList[self.y],imageName+'.jpg')
imgfile = Image.open(imageName+'.jpg')
imgfile = imgfile.resize((150,150),Image.ANTIALIAS)
# img = Image.open(file)
self.threadImage = ImageTk.PhotoImage(imgfile)
self.threadLabelImage.config(text = self.threadImage)
self.threadImage.image = imgfile
And here is the entire program so you can run it if need be.import xml.etree.ElementTree as ET
import webbrowser,time,urllib.request,re
import tkinter as tk
import urllib
from PIL import Image,ImageTk
main = tk.Tk()
class Application(tk.Frame):
def __init__(self, master=None):
self.threadTitle = tk.StringVar()
self.threadAuth = tk.StringVar()
self.threadPub = tk.StringVar()
self.threadArtLink = tk.StringVar()
self.threadLink = tk.StringVar()
self.threadImg = tk.StringVar()
self.threadArtLink.set('Click something to display thread info')
photo = Image.open("temp.png")
photo = photo.resize((150,150), Image.ANTIALIAS)
self.threadImage = ImageTk.PhotoImage(photo)
# Intializes tkinter gui framework
tk.Frame.__init__(self, master)
# Packs widgets needed
self.grid()
# Creates the widgets functions
self.createWidgets()
# Intializes the man rss.xml
self.initial()
# self.threadLabelArtLink = None
# self.threadLabelTitle = None
# self.threadLabelThreadLink = None
# self.threadLabelArtLink = None
# self.threadImgLink = None
def createWidgets(self):
# Create entrybox and align to grid
self.send_entry = tk.Entry(self)
self.send_entry.grid(row=0,column=0)
# Create button,allign to grid, get xml
self.change_sub = tk.Button(self,text='Change Subreddit',padx=5, pady=5, command=lambda :self.getXML(self.send_entry.get())).grid(row=0 , column=3)
# Create scrollbar on Y-Axis
self.lb_scrollY = tk.Scrollbar(self,orient=tk.VERTICAL)
# On grid next to Listbox(sticky means fill whole row
self.lb_scrollY.grid(row=1,column=4,sticky=tk.NS,rowspan=6)
# Create Listbox and get Y from scrollbar
self.thread_lb = tk.Listbox(self,yscrollcommand=self.lb_scrollY.set,height=20)
# Calls function whenever a new item is selected
self.thread_lb.bind('<<ListboxSelect>>',self.updateSelected)
self.thread_lb.bind('<Double-Button-1>',self.openPage)
# scrolly will change the view of listbox
self.lb_scrollY['command']=self.thread_lb.yview
self.thread_lb.grid(row=1,column=0,sticky=tk.NS+tk.EW,columnspan=4)
self.threadFrame = tk.LabelFrame(main,text='Reddit',width=450,height=350,labelanchor='n')
self.threadLabelTitle = tk.Label(self.threadFrame,textvariable=self.threadTitle,wraplength=400,padx=20, pady=5).grid(row=1,column=10,sticky= tk.EW)
self.threadLabelAuth = tk.Label(self.threadFrame, textvariable=self.threadAuth,wraplength=400,padx=20, pady=5).grid(row=2,column=10,sticky = tk.EW)
self.threadLabelPub = tk.Label(self.threadFrame, textvariable=self.threadPub,wraplength=400,padx=20, pady=5).grid(row=3,column=10,sticky = tk.EW)
self.threadLabelArtLink = tk.Label(self.threadFrame, textvariable=self.threadArtLink,wraplength=400,padx=20, pady=5).grid(row=4,column=10,sticky = tk.EW)
self.threadLabelThreadLink = tk.Label(self.threadFrame, textvariable=self.threadLink,wraplength=400,padx=20, pady=5).grid(row=5,column=10,sticky = tk.EW)
self.threadImgLink = tk.Label(self.threadFrame, textvariable=self.threadImg,wraplength=400,padx=20, pady=5).grid(row=6,column=10,sticky = tk.EW)
self.threadLabelImage = tk.Label(self.threadFrame,image=self.threadImage,wraplength=400,padx=20,pady=5).grid(row=7,column=10,sticky = tk.EW)
self.threadFrame.grid(row=0,column=10,sticky=tk.EW,rowspan=8)
self.threadFrame.grid_propagate(0)
self.QUIT = tk.Button(self, text="QUIT", fg="red", command=main.destroy,padx=5, pady=5).grid(row=7)
def updateSelected(self, event):
# getting selected listbox item
i=self.thread_lb.curselection()
# Returns tuple that must be split
x,self.y,z = re.split("\D+",str(i))
self.y=int(self.y)
print(self.threadTitleList[self.y])
print(self.threadPubDateList[self.y])
print(self.threadLinkList[self.y])
print(self.threadDescList[self.y])
self.threadTitle.set(self.threadTitleList[self.y])
self.threadAuth.set(self.threadAuthList[self.y])
self.threadPub.set(self.threadPubDateList[self.y])
self.threadArtLink.set(self.threadLinkList[self.y])
self.threadLink.set(self.threadDescList[self.y])
self.threadImg.set('Will put image here')
if self.threadLinkList[self.y].find('imgur') != -1:
url = self.threadLinkList[self.y]+'.GIF'
imageName=self.threadLinkList[self.y][-11:-4]
urllib.request.urlretrieve(self.threadLinkList[self.y],imageName+'.jpg')
imgfile = Image.open(imageName+'.jpg')
imgfile = imgfile.resize((150,150),Image.ANTIALIAS)
# img = Image.open(file)
self.threadImage = ImageTk.PhotoImage(imgfile)
self.threadLabelImage.config(text = self.threadImage)
self.threadImage.image = imgfile
# # threadTitle = self.threadTitleList[y]
# print(self.threadLabelTitle["text"])
# # self.threadLabelTitle['text']=threadTitle
# self.threadLabelAutPub['text']=self.threadPubDateList[y]
# self.threadImgLink['text']=self.threadLinkList[y]
# self.threadLabelThreadLink['text']=self.threadDescList[y]
# main.update()
def openPage(self,event):
webbrowser.get('windows-default').open_new(self.threadLinkList[self.y])
def descStripper(self,desc):
# Intialize values
l1,l2,l2Start = 0,0,0
t1,t2,t2start = 0,0,0
link = ""
thread = ""
# Where to start looking for each in description element
l1=int(desc.find('<br/> <a href="'))
t1=int(desc.find('</a> <a href="'))
a1=int(desc.find('"> '))
# If both of the tags are found then continue
if l1 != -1 and t1 != -1 and a1 != 1:
# Start looking for end of quotes 16 characters from beginning of tag
l2Start = l1+16
l2=int(desc.find('"',l2Start))
# Link is created from what is in the quotes
link = desc[l1+15:l2]
# Same as above but to find thread link
t2start = t1+15
t2=int(desc.find('"',t2start))
thread = desc[t1+14:t2]
a2start = a1+4
a2 = int(desc.find(' <',a2start))
author = desc[a1+3:a2]
return link,thread,author
else:
# If it can't find one it will return an error
link = "Couldn't find the stuff :("
thread = "Couldn't find the thread link :("
return link, thread
def lbPopulator(self,title,pub,link):
# Delete old entries from listbox
self.thread_lb.delete(0,tk.END)
# Iterate through all the items and append them to the listbox
for item in title:
self.thread_lb.insert(tk.END,item)
def getXmlData(self):
# Intialize lists
self.threadPubDateList = []
self.threadTitleList = []
self.threadLinkList = []
self.threadDescList = []
self.threadThumbNailList = []
self.threadAuthList = []
# Use the downloaded rss.xml for XML parsing
tree=ET.parse('rss.xml')
# define root as the base of the XML parsing tree
root=tree.getroot()
for channel in root:
# Iterate through all the channels
for SubChannel in channel:
# Iterate through all the items in the channel
if SubChannel.tag == 'item':
# If the SubChannel is called item then search for the items below
for threadInfo in SubChannel:
# iterate through all the items in the 'item'
if threadInfo.tag == 'title':
# append the tag from the title to the list
self.threadTitleList.append(threadInfo.text)
if threadInfo.tag == 'pubDate':
# Append the pubdate info to the list but remove excess characters
self.threadPubDateList.append(threadInfo.text[:-6])
if threadInfo.tag == 'description':
# Pass all the information from the description to the stripper to get the useful
# information and links
link,thread,author = self.descStripper(threadInfo.text)
self.threadLinkList.append(link)
self.threadDescList.append(thread)
self.threadAuthList.append(author)
# if threadInfo.tag == ''
# Populate the listbox with the newly generated lists
self.lbPopulator(self.threadTitleList,self.threadPubDateList,self.threadLinkList)
def getXML(self,subreddit):
try:
# Try to download the xml file using the user input subreddit
url = 'http://www.reddit.com'+subreddit+'.rss'
source = urllib.request.urlretrieve(url,'rss.xml')
self.getXmlData()
except urllib.error.HTTPError as err:
# Error caused by reddit API limiting connections
print('Too many requests-Try again')
def initial(self):
try:
# Same as above but downloads the front page
source = urllib.request.urlretrieve('http://www.reddit.com/.rss','rss.xml')
self.getXmlData()
except urllib.error.HTTPError as err:
print('Too many requests-Trying again 3')
# If error occurs program waits 3 seconds and then restarts
time.sleep(3)
self.__init__()
# main.geometry("350x400")
app = Application(master=main)
# Begins the applications GUI loop
app.mainloop()
The grid method of a Tkinter widget always returns None. So, any calls to it must be placed on their own line.
Meaning, all of the lines that are written like this:
self.threadLabelTitle = tk.Label(self.threadFrame,textvariable=self.threadTitle,wraplength=400,padx=20, pady=5).grid(row=1,column=10,sticky= tk.EW)
need to be rewritten like this:
self.threadLabelTitle = tk.Label(self.threadFrame,textvariable=self.threadTitle,wraplength=400,padx=20, pady=5)
self.threadLabelTitle.grid(row=1,column=10,sticky= tk.EW)

Categories

Resources