I have quick question, and it may sound dumb. But for the love of me I can't find a solution online or by myself! I am trying to make a FTP client using python for my self, and I am trying to make a listbox in Tkinter display all the filenames on the FTP server. But I can't get the text to display! Here is the code I have so far below:
# Import the FTP object from ftplib
from ftplib import FTP
from Tkinter import *
app = Tk()
app.title("FTP")
app.geometry("300x500")
def handleDownload(block):
file.write(block)
print ".",
def login():
ftp.login(username.get(),password.get())
# This is where I am held up I tried ftp.retrlines('LIST') but it would
# not be inserted into to the list box instead it inserted "Tranfer Complete" at the end!
# Any suggetion?
h = ?
stuff = Listbox(app)
stuff.insert(END, h)
stuff.pack()
filename = "Steam Engine Poster.pdf"
Label(app, text ='Opening local file ' + filename).pack()
file = open(filename, 'wb')
Label(app, text = "Downloading Steam Engine Poster.pdf").pack()
ftp.retrbinary('RETR ' + filename, handleDownload)
Label(app, text = "Closing FTP connection!").pack()
ftp.close()
ftp = FTP('sciphigames.com')
Label(app, text = "Login").pack()
username = StringVar(None)
username = Entry(app, text = "Username: ")
username.pack()
password = StringVar(None)
password = Entry(app, text = "Password: ")
password.pack()
button = Button(app, text = "Login!", command = login)
button.pack()
app.mainloop()
You get "Transfer Complete" because retrlines returns the response code, not the listing. If you check the documentation, you'll see that apart from the command, there's a second argument, a callback, that will be called for each line returned. By default it just prints the line to the standard output.
lines = []
def append_line(line):
lines.append(line)
ftp.retrlines('LIST', append_line)
Related
I am working on a standalone desktop app to generate a list of random passwords that are saved to a text file. I was able to create a working code in PyCharm that creates a text file there with a list of random passwords based on length of password and how many passwords to create. This works perfectly.
import random
import csv
password_len = int(input("What length would you like your password to be : "))
password_count = int(input("How many passwords would you like : "))
Chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
while 1:
pwfile = open('passwords.txt','w')
for x in range(0, password_count):
password = ""
for x in range(0, password_len):
password_char = random.choice(Chars)
password = password + password_char
pwfile.write(password + '\n')
pwfile.close()
The issue I am running into is when I try to create the desktop app with Tkinter, I cannot seem to get the app to write to a text file. The code creates the pop up window and asks for the password length and how many. But after I enter those numbers and attempt to generate the file, the app just freezes. I think maybe the problem is I'm trying to write and save in the same function? Here is the code:
from tkinter import *
import random
import csv
root = Tk()
root.title('Password Server Generator')
root.geometry('400x600')
def PWgen():
Chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
pw_count = int(passTextbox.get())
pw_length = int(myTextbox.get())
while 1:
pwfile = open('passwords.txt', 'w')
for x in range(0, pw_count):
password = ""
for x in range(0, pw_length):
password_char = random.choice(Chars)
password = password + password_char
pwfile.write(password + '\n')
#Text asking for password length
password_len = Label(root, text="What length would you like your passwords to be : ")
password_len.pack()
#Box to enter password length
myTextbox = Entry(root, width=30)
myTextbox.pack()
#Text asking for how many passwords to generate
password_count = Label(root,text="How many passwords would you like to generate: ")
password_count.pack()
#Box to enter how many passwords to generate
passTextbox = Entry(root, width=30)
passTextbox.pack()
#Button to generate password list
myButton = Button(root, text="Generate Password", command=PWgen)
myButton.pack()
root.mainloop()
Ideally this would automatically create a password.txt file or give an option to save to desktop or automatically save to desktop. Any option is fine I just can't figure out what I'm doing incorrectly. I tried adding a pwfile.close() to the end of the app loop but that still just crashes. Any advice would be greatly appreciated.
I'm trying to close a pdf file using a Tkinter button but I can't find any suitable solution for my problem. I'm using a raspberry pi with Raspbian operating system
I've tried the kill() function but my pdf file is not closing.
Here's my code to open a pdf file
class Thesis():
self.packet = io.BytesIO()
self.can = canvas.Canvas(self.packet, pagesize = letter)
self.can.drawString(250,250, "Hello World")
self.can.save()
self. packet.seek(0)
self.new_pdf = PdfFileReader(self.packet)
self. existing_pdf = PdfFileReader(open("Sample.pdf", "rb"))
self.existing _pdf.decrypt('')
self.output = PdfFileWriter()
self.page = self.existing_pdf.getPage(0)
self.page.mergePage(self.new_pdf.getPage(0))
self.outpute.addPage(self.page)
self.outputStream = open("destination.pdf", "wb")
output.write(self.outpuStream)
self.opener ="open" if sys.platform == "darwin"else "xdg-open"
subprocess.call([self.opener, "destination.pdf"])
#create print button
self.print_root = Toplevel()
self.print_root.geometry("+910+635")
self.print_button = Button(self.print_root, text ="Print", width = 10, height = 5, command = self.print_form)
self.print_button.pack()
def print_form(self):
#code to close a pdf file after clicking a print button.
self.filename = "/home/pi/Thesis/barangay_certification_result.pdf"
self.p = subprocess.Popen("exec " + filename, stdout=subprocess.PIPE, shell = True)
self.p.kill()
all I have to do is to totally close the pdf file, completely terminated.
I am doing the Final Year Project about the GUI of Aircrack-ng. In my GUI design, the result of cracking password will be write into the text file. And that i write the code to read the text file and display the content what i need . Now i can display some information(Target AP,ESSID ,KEY) on the testbox. I also need to display the ASCII password. I have to refer the document about re (https://docs.python.org/2/library/re.html) and try it but not successful. I hope someone can teach me how to do.Thank you.
This is the text file about the result of cracking password
https://drive.google.com/open?id=192IQr5Y2VUjIZBdUrAlD5uyQQ8YSOUDw
This is the function and GUI Design about display the detail for wep password
# Use pandas to filter the results and display to textbox
def wepresult():
result = re.search(r"\[([^[]+[^(])\]", wepcrackresult_text.get("1.0", 'end-1c'))
if result:
wepcrackresult_text.delete(0.0, END)
wepcrackresult_text.insert(INSERT, "Target ESSID: " + self.controller.shared_data[
"ESSID"].get() + "\nTarget MAC address: " + self.controller.shared_data[
"BSSID"].get() + "\nKEY:" + result.group(1))
GUI Design
wepcrackresult_button = tk.Button(self, text='4.Check', font='Verdana 14',command = wepresult)
wepcrackresult_button.place(x=2, y=630)
Below is the simplest code I can think of:
import tkinter as tk
def display_file(file_path):
txt.delete('1.0', 'end')
with open(file_path) as f:
file_content_as_string = f.read()
# regex filterings can be made in filte_content_as_string
txt.insert('1.0', file_content_as_string)
if __name__ == '__main__':
root = tk.Tk()
txt = tk.Text(root)
# replace __file__ with path
display_file(__file__)
txt.pack()
root.mainloop()
This might be a strange question because I am new to Python.
I am trying to create form in Python which data can be entered into boxes and saved, then opened again. I'm currently using Tkinter to create a Gui which has entry boxes and buttons:
import sys
from tkinter import *
def mstore():
pass
return
def msearch():
file_path = filedialog.askopenfilename()
return
mGui=Tk()
mGui.geometry('450x450+200+200')
mGui.title('Form Test')
#Top
mTitle = Label (mGui,text='Heading Text',bg='white').grid(row=1,column=1)
mDetail = Label (mGui,text='Flavour you can see',bg='white').grid(row=2,column=1)
#Entry Boxes
mFName = Label (mGui,text='Barcode',bg='white').grid(row=3,column=1)
mEntryname = Entry().grid(row=3,column=2)
#Buttons
mSave = Button (mGui,text='Save',bg='white', command = mstore).grid(row=4,column=1)
mSearch = Button (mGui,text='Search',bg='white', command = msearch).grid(row=5,column=1)
mGui.mainloop()
The search was going to be used to open up a file which has been saved before and fill in the boxes with that data, however before that I need help saving the data in a way it will be retrievable - All the information I find is about web-forms. I have also tried saving information with SQLite3 but I found that to not be quite what I was looking for.
Any help/guidance will be appreciated.
Thanks,
Hello Gregulimy!
I have simplified your code and made it do what you want it to do. I have left comments explaining what the code does. If you have any questions about what I have done feel free to ask!
from tkinter import *
def mstore(text):
file = open("file.txt", "w") # Create file.txt
file.write(text) # Write contents of mEntryname to file
file.close() # Closes text file
def msearch():
file = filedialog.askopenfilename() # Stores file directory that user chose
open_file = open(file, 'r') # Opens file user chose
print(open_file.read()) # Displays contents in console
open_file.close() # Closes text file
# Window Creation and Settings
window = Tk()
window.geometry('450x500')
window.title('Form Test')
# Create Widgets
mTitle = Label (window,text='Heading Text',bg='white')
mDetail = Label (window,text='Flavour you can see',bg='white')
mFName = Label (window,text='Barcode',bg='white')
mEntryname = Entry(window)
# Runs mstore function when pressed (passing the contents of the entry box)
mSave = Button (window,text='Save',bg='white', command = lambda: mstore(mEntryname.get()))
# Runs msearch function when pressed
mSearch = Button (window,text='Search',bg='white', command = lambda: msearch())
# Render Widgets
mTitle.pack()
mDetail.pack()
mFName.pack()
mEntryname.pack()
mSave.pack()
mSearch.pack()
window.mainloop()
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