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)
Related
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) ```
I am trying to display a popup window that will show the results from an API using PySimple GUI call after the user has selected an item, but nothing is showing when the button is being clicked.
import PySimpleGUI as sg
# import PySimpleGUIQt as sg
import os.path
import PIL.Image
import io
#import imutils
import requests
import base64
import json
import base64
from detect_face_video import main
"""
"""
plate='f'
def convert_to_bytes(file_or_bytes, resize=None):
'''
Will convert into bytes and optionally resize an image that is a file or a base64 bytes object.
Turns into PNG format in the process so that can be displayed by tkinter
:param file_or_bytes: either a string filename or a bytes base64 image object
:type file_or_bytes: (Union[str, bytes])
:param resize: optional new size
:type resize: (Tuple[int, int] or None)
:return: (bytes) a byte-string object
:rtype: (bytes)
'''
if isinstance(file_or_bytes, str):
img = PIL.Image.open(file_or_bytes)
else:
try:
img = PIL.Image.open(io.BytesIO(base64.b64decode(file_or_bytes)))
except Exception as e:
dataBytesIO = io.BytesIO(file_or_bytes)
img = PIL.Image.open(dataBytesIO)
cur_width, cur_height = img.size
if resize:
new_width, new_height = resize
scale = min(new_height/cur_height, new_width/cur_width)
img = img.resize((int(cur_width*scale), int(cur_height*scale)), PIL.Image.ANTIALIAS)
with io.BytesIO() as bio:
img.save(bio, format="PNG")
del img
return bio.getvalue()
def update_plate(filename):
SECRET_KEY = 'sk_ed3d203bf4c9a7c2910ec0c0'
with open(filename, 'rb') as image_file:
img_base64 = base64.b64encode(image_file.read())
url = 'https://api.openalpr.com/v3/recognize_bytes?recognize_vehicle=1&country=us&secret_key=%s' % (SECRET_KEY)
r = requests.post(url, data = img_base64)
try:
global plate
plate=r.json()['results'][0]['plate'],
global Brand
Brand= r.json()['results'][0]['vehicle']['make_model'][0]['name'],
global Color
Color= r.json()['results'][0]['vehicle']['color'][0]['name'],
print(plate)
except:
print ('error')
# --------------------------------- Define Layout ---------------------------------
# First the window layout...2 columns
sg.theme('Dark Blue 3')
left_col = [[sg.Text('Folder'), sg.In(size=(25,1), enable_events=True ,key='-FOLDER-'), sg.FolderBrowse()],
[sg.Listbox(values=[], enable_events=True, size=(40,20),key='-FILE LIST-')],
[sg.Text('Resize to'), sg.In(key='-W-', size=(5,1)), sg.In(key='-H-', size=(5,1))],
[sg.Button("Resize", button_color=("white", "blue"), size=(6, 1))]]
# For now will only show the name of the file that was chosen
images_col = [[sg.Text('You choose from the list:')],
[sg.Text(size=(40,1), key='-TOUT-')],
[sg.Image(key='-IMAGE-')]]
# ----- Full layout -----
layout = [[sg.Column(left_col, element_justification='c'), sg.VSeperator(),sg.Column(images_col, element_justification='c')]]
# --------------------------------- Create Window ---------------------------------
window = sg.Window('Multiple Format Image Viewer', layout,resizable=True)
# ----- Run the Event Loop -----
# --------------------------------- Event Loop ---------------------------------
while True:
event, values = window.read()
if event in (sg.WIN_CLOSED, 'Exit'):
break
if event == sg.WIN_CLOSED or event == 'Exit':
break
if event == '-FOLDER-': # Folder name was filled in, make a list of files in the folder
folder = values['-FOLDER-']
try:
file_list = os.listdir(folder) # get list of files in folder
except:
file_list = []
fnames = [f for f in file_list if os.path.isfile(
os.path.join(folder, f)) and f.lower().endswith((".png", ".jpg", "jpeg", ".tiff", ".bmp"))]
window['-FILE LIST-'].update(fnames)
if event == 'Resize':
window['-IMAGE-'].update(data=convert_to_bytes(filename, resize=new_size))
elif event == '-FILE LIST-': # A file was chosen from the listbox
try:
filename = os.path.join(values['-FOLDER-'], values['-FILE LIST-'][0])
window['-TOUT-'].update(filename)
if values['-W-'] and values['-H-']:
new_size = int(values['-W-']), int(values['-H-'])
else:
new_size = None
window['-IMAGE-'].update(data=convert_to_bytes(filename, resize=new_size))
main(filename)
update_plate(filename)
print(plate)
except Exception as E:
print(f'** Error {E} **')
pass # something weird happened making the full filename
# --------------------------------- Close & Exit ---------------------------------
window.close()
Setting keep on top in the Popup call created the window on top for me. Just add
sg.Popup("license plate" , plate , keep_on_top=True)
However, if you click on the window behind, because it also has keep on top set, it will cover your popup.
I'm trying to set up a GUI feature that allows users to click a button, then be quizzed on/input new words in the categories 'nouns,' 'verbs,' 'adjectives,' etc. The program I have set up references .txt files saved in the same directory as the program.
I haven't been able to pass arguments to buttons, and the answers I've found suggest using lambda functions in some simple situations. The program works if I remove all passed arguments and simply assign a specific file (farsi_nouns, etc.) within each function. I'm not able to tell if I'm doing this incorrectly, or if Tkinter is too basic a GUI to pass arguments to functions in this way. Thanks very much for any feedback!
Tkinter ver. 8.5, Python 3.5.2, OSx High Sierra 10.13.4.
file_in_use = 'farsi_words'
def defaultFile(filename):
file_in_use = filename
return file_in_use
bN = Button(f0, text = 'Nouns', command =lambda: defaultFile('farsi_words'))
bN.pack(side='left')
bN.bind("<Button-1>",
bV = Button(f0, text = 'Verbs', command =lambda: defaultFile('farsi_verbs'))
bV.pack(side='left')
bA = Button(f0, text = 'Adjectives', command =lambda: defaultFile('farsi_adjectives'))
bA.pack(side='left')
bP = Button(f0, text = 'Prepositions', command =lambda: defaultFile('farsi_preps'))
bP.pack(side='left')
def commit(file_in_use):
word = e1.get()
definition = e2.get()
appendFile = open(file_in_use, 'a')#was this defined before def?
appendFile.write('\n' + word + ': ' + definition)
appendFile.close()
e1.delete(0, 'end')
e2.delete(0, 'end')
def review(file_in_use):
t1.delete('1.0', END)
readFile = open(file_in_use, 'r')
size = 0
splitList = []
for line in readFile:
splitWord = line.split(':')
splitWord = splitWord[0].strip('\n ')
splitList.append(splitWord)
size += 1
n = random.randint(0, size - 1)
t1.insert(INSERT, splitList[n] + '\n')
readFile.close()
def answer(file_in_use):
word = e3.get()
def1 = t1.get('1.0','end-1c')
def1 = def1.strip('\n')
readFile = open(file_in_use, 'r')
for line in readFile:
splitWord = line.split(': ')
if def1 == splitWord[0].strip('\n'):
if word == splitWord[1].strip('\n'):
t1.insert(INSERT, 'Good job!')
else:
t1.insert(INSERT, 'Not quite! Good try =)')
readFile.close()
def hint(file_in_use):
def1 = t1.get('1.0','2.0')
def1 = def1.strip('\n')
readFile = open(file_in_use, 'r')
for line in readFile:
splitWord = line.split(': ')
if def1 == splitWord[0].strip('\n'):
hint = splitWord[1]
hint1 = t1.get('2.0','end-1c')
lenHint1 = len(hint1)
if lenHint1 >= len(hint):
pass
else:
t1.insert(INSERT, hint[lenHint1])
print (hint1)
readFile.close()
You can pass arguments easily if you put your code in a class. Another thing is the tkinters function .after() you can try. I have made a simple GUI for demonstration of both.
import tkinter as tk
from tkinter import *
class GUI:
def __init__(self, master):
self.file_in_use = 'farsi_words'
self.master = master
self.bN = Button(master, text = 'Nouns', command = self.farsi_words)
self.bN.pack(side='left')
self.bN.bind("<Button-1>")
self.bV = Button(master, text = 'Verbs', command = self.farsi_verbs)
self.bV.pack(side='left')
self.bA = Button(master, text = 'Adjectives', command = self.farsi_adjectives)
self.bA.pack(side='left')
self.bP = Button(master, text = 'Prepositions', command = self.farsi_preps)
self.bP.pack(side='left')
def farsi_words(self, event=None):
self.file_in_use = 'Nouns'
self.master.after(1, self.commit)
def farsi_verbs(self, event=None):
self.file_in_use = 'Verbs'
self.master.after(1, self.commit)
def farsi_adjectives(self, event=None):
self.file_in_use = 'Adjectives'
self.master.after(1, self.commit)
def farsi_preps(self, event=None):
self.file_in_use = 'Prepositiones'
self.master.after(1, self.commit)
def commit(self, event=None):
print(self.file_in_use)
if __name__ == "__main__":
root = Tk()
my_gui = GUI(root)
root.mainloop()
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)
I am using Tkinter to help me build a FTP client, in this client I am trying to get the selected information from a tk listbox. So I have a button that starts the download but what ever the reason is it pops up with the error "
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1410, in __call__
return self.func(*args)
File "/Volumes/LEGO FLASH/ftp.py", line 23, in Download
filename = stuff
NameError: global name 'stuff' is not defined"
Below I have the code for you to look at:
# Import the FTP object from ftplib
from ftplib import FTP
from Tkinter import *
import os
app = Tk()
app.title("FTP")
app.geometry("300x300")
lines = []
#[lines.replace(",", "\n")for lines in lines]
#lines = lines.replace(',','\n')
def handleDownload(block):
file.write(block)
print ".",
def append_line(line):
lines.append(line)
#This is where I am caught------->
def Download():
filename = stuff
file = open(filename, 'wb')
ftp.retrbinary('RETR ' + filename, handleDownload)
ftp.close()
def login():
try:
ftp.login(username.get(),password.get())
except:
error = Label(app, text = "Invalid USERNAME OR PASSWORD")
label2 = Label(app, text = "Welcome to Steam Engine").pack()
username.forget()
password.forget()
button.forget()
app.geometry("800x500")
download = Button(app, text = "Download!!!!!", command = Download)
download.pack(side = "left", pady = "5")
scrollBar.pack(fill = Y, side = "right", padx = "2")
#ftp.cwd('The_Store')
stuff = Listbox(app, height = "700", width = "500")
ftp.retrlines('NLST', append_line)
for i in lines:
stuff.insert(END, i)
stuff.pack(padx = "10", pady = "10")
stuff.config(yscrollcommand = scrollBar.set)
scrollBar.config(command = stuff.yview)
ftp = FTP('sciphigames.com')
label = Label(app, text = "Login").pack(pady = "10")
scrollBar = Scrollbar(app)
username = StringVar(None)
username = Entry(app, text = "Username: ")
username.pack(pady = "2")
password = StringVar(None)
password = Entry(app, text = "Password: ")
password.pack(pady = "2")
button = Button(app, text = "Login!", command = login)
button.pack(pady = "10")
app.mainloop()
Any help would be appreciated!
Thanks!
#This is where I am caught------->
def Download():
filename = stuff
what is stuff here ?? it is not a global variable, it seems to be a parameter of login, but not of Download method.
If you want to do stuff a global variable (probably not the better choice), use the global statement.
# Import the FTP object from ftplib
from ftplib import FTP
from Tkinter import *
import os
# define the global stuff
global stuff
...
def Download():
global stuff
filename = stuff
...
A better way to handle this would be to create an object around all of this ::
class NetworkApp(object):
def login(self):
# here put all the previous code of login
# here we change the callback to self.Download
download = Button(app, text = "Download!!!!!", command = self.Download)
# here we're creating a stuff member
self.stuff = Listbox(app, height = "700", width = "500")
def Download(self):
filename = self.stuff # here we use the stuff member
file = open(filename, 'wb')
ftp.retrbinary('RETR ' + filename, handleDownload)
ftp.close()
#...
net_app = NetworkApp()
button = Button(app, text = "Login!", command = net_app.login)
I am not entirely sure what the purpose is with your stuff variable, but the problems you are experiencing probably stem from the way you are using it.
First, you are using it as argument to login (which, by the way should take no arguments). You assign to this variable from the login function, and refer to another variable with the same name in your Download function.
Again, not being sure what I understand what you want to do with the stuff variable, I would try something like
.....
app.geometry("300x300")
stuff = None # <<<<----
lines = []
.....
#This is where I am caught------->
def Download():
global stuff # <<<<----
filename = stuff
......
ftp.close()
def login():
global stuff # <<<<----
......
stuff = Listbox(app, height = "700", width = "500")
ftp.retrlines('NLST', append_line)
for i in lines:
stuff.insert(END, i)
stuff.pack(padx = "10", pady = "10")
stuff.config(yscrollcommand = scrollBar.set)
scrollBar.config(command = stuff.yview)
......
All you need to do is put "global" in front of the variable
global var1