I've been trying to run this simple test just to get the feel of how to import methods from another script, but I have two problems:
the whole program runs instead of just importing and calling, the methods, when I need them too.
I'm getting this error:
Traceback (most recent call last):
File "C:\Users\devilboy 4\Documents\Visual Studio 2013\Projects\classvariablesOnANewScript\classvariablesOnANewScript\classvariablesOnANewScript.py", line 1, in <module>
from logInScreen import getUser, getPass
ImportError: cannot import name getUser
This is the script I'm importing to:
from logInScreen import getUser, getPass
class hello:
def show(self):
usr = getUser()
ps = getPass()
str(usr)
str(ps)
h = hello()
h.show()
This is what's on logInScreen.py :
from tkinter import *
import os
import tkinter.messagebox
#check si lo entrado es correcto
class checkValidation:
fail = 0
user = "hi user"
password = "nice pass"
#valida el user y el pass
def fullVali(self, name, passwd):
if name == "" or name == " ":
tkinter.messagebox.showinfo( "Error","Dejo el usuario en blanco")
self.fail+= 1
elif name != "UmetSeg":
tkinter.messagebox.showinfo( "Error","Usuario incorrecto")
self.fail+= 1
else :
self.user = name
tkinter.messagebox.showinfo( "ok","dude" + name)
if passwd == "" or passwd == " ":
tkinter.messagebox.showinfo( "Error","Dejo la password en blanco")
self.fail+= 1
elif passwd != "SegUmet":
tkinter.messagebox.showinfo( "Error","Password incorrecto")
self.fail+= 1
else:
self.password = passwd
tkinter.messagebox.showinfo( "ok","dude" + passwd)
form.destroy()
#open another py script
#os.system("mainPage3.py 1")
return
# no deja pasar parametros por command en el boton a menos que se por lambda, so corre #este metodo para
#correr el metodo de validar
def callVali(self):
user = usrIn.get()
self.fullVali(usrIn.get(), passIn.get())
return
def getUser(self):
return self.user
def getPass(self):
return self.password
vali = checkValidation()
form = Tk()
form.title("LogIn")
form.geometry("300x320+300+200")
#User txtBox
usrIn = Entry(form, textvariable = None, width = 30)
usrIn.place(x = 60, y = 140)
user = usrIn.get()
#Passwd txtBox
passIn = Entry(form, textvariable = None, width = 30)
passIn.place(x = 60, y = 200)
#Username Label
usrLblVal = StringVar()
usrLblVal.set("User name")
usrLbl = Label(form, textvariable = usrLblVal )
usrLbl.place(x = 120, y = 115)
#Passwrd label
passLblVal = StringVar()
passLblVal.set("Password")
passLbl = Label(form, textvariable = passLblVal )
passLbl.place(x = 120, y = 175)
#Login btn
btn = Button(form, text = "Entrar", width = 10, command = vali.callVali)
btn.place(x = 110, y = 250)
form.mainloop()
I hope I got the indentation right, kinda off a pain going through every line and spacing 4 times till it's right. I apologize for the Spanish, just ignore all the comments lol
You are attempting to import methods from within a class in your LogInScreen.py file. The methods getUser and getPass are bound methods that belong to the class checkValidation, You need to instead import the class and make the call on your class instead
from LogInScreen import checkValidation
validation = checkValidation()
validation.getUser()
validation.getPass()
As a simple illustration consider the following example involving two files:
file_to_import_from.py (Analogous to your logInScreen.py)
class MyClass:
def my_class_bound_method(self):
print "hello I a method belonging to MyClass"
def my_method_not_belonging_to_a_class():
print "Hello, I am a method that does not belong to a class"
file_to_import_to.py (Analogous to the script you are importing to)
from file_to_import_from import my_method_not_belonging_to_a_class
my_method_not_belonging_to_a_class()
from file_to_import_from import MyClass
x = MyClass()
x.my_class_bound_method()
from file_to_import_from import my_class_bound_method
my_class_bound_method()
And see Output
Hello, I am a method that does not belong to a class
hello I a method belonging to MyClass
Traceback (most recent call last):
File "C:\Users\Joe\Desktop\Python\import_test2.py", line 10, in <module>
from file_to_import_from import my_class_bound_method
ImportError: cannot import name my_class_bound_method
As you can see, the first two calls worked, but the second time the error you are facing arose, this is because the method my_class_bound_method exists as a method within the class MyClass.
EDIT:
In response to your comment, to avoid running the whole file, surround the code in your 'LogInScreen.py' in an if statement which checks if the file being evaluated by the interpreter is the main file being run.
from tkinter import *
import os
import tkinter.messagebox
#check si lo entrado es correcto
class checkValidation:
# CODE FROM YOUR CLASS OMITTED FOR BREVITY SAKE
# NOTHING BEYOUND THIS IF STATEMENT WILL RUN WHEN THE FILE IS IMPORTED
if __name__ == "__main__":
vali = checkValidation()
# MORE CODE OMITTED FOR BREVITY
form.mainloop()
The if statement I added here checks a special environment variable that python creates when it interprets a file, which is __name__, when the file is the file that you are directly running: python file_i_am_running.py the variable __name__ is set the the string "__main__" to indicate it is the main method, when it is not the file being run, and maybe one being imported as in your case, the variable is set to the module name, i.e. file_to_import.
Change to this:
from logInScreen import checkValidation
And then, use:
check = checkValidation()
usr = check.getUser()
ps = check.getPass()
Related
I am currently working on a simple Oregon Trail clone for a school project. I want to use Tkinter for this game, since the current version for pygame only goes up to Python 2 and I am used to using Python 3. I separated the different parts of the game into separate py files (main.py, names.py, occupations.py, store.py, game.py) and put them all into a folder so it is more organized. I already typed out the code for the welcome screen and the code for main.py, names.py, and a little for occupations.py. When I run my code, I am presented with an error that that the name 'names' is not defined. In the names file, I created a function called names() and a ran it in the main file. What is wrong with my code?
# main.py
from tkinter import *
from names import *
from occupations import *
from store import *
from game import *
root = Tk()
root.resizable(width=True, height=True)
root.wm_title('Oregon Trail')
root.geometry("200x75")
canvas = Canvas(root,width=400,height=200)
canvas.pack()
welcome = Label(canvas,
font = ('System',14,'bold'),
text = 'Oregon Trail')
welcome.grid(row=0,sticky=(N,S,E,W))
play = None
def playbuttoncommands():
canvas.pack_forget()
play.grid_forget()
welcome.grid_forget()
names()
play = Button(canvas,
font = 'System',
text = 'Travel the Trail',
command = playbuttoncommands)
play.grid(row=1,sticky=(N,S,E,W))
root.mainloop()
# names.py
from tkinter import *
from occupations import *
from store import *
from game import *
from main import *
def names():
canvas2 = Canvas(root,width=400,height=200)
canvas.pack()
root.geometry("400x200")
namelabel = Label(root,
font = 'System',
text = 'Please enter the names of your travel group:')
namelabel.grid(row=1,sticky=N)
name1 = ''
name1entry = Entry(root,textvariable=name1)
name1entry.grid(row=2,sticky=N)
name2 = ''
name2entry = Entry(root,textvariable=name2)
name2entry.grid(row=3, sticky=N)
name3 = ''
name3entry = Entry(root,textvariable=name3)
name3entry.grid(row=4,sticky=N)
name4 = ''
name4entry = Entry(root,textvariable=name4)
name4entry.grid(row=5,sticky=N)
name5 = ''
name5entry = Entry(root,textvariable=name5)
name5entry.grid(row=6,sticky=N)
enternames = Button(text = 'Continue', command = submitnames)
enternames.grid(row=7,sticky=N)
# occupations.py
from tkinter import *
from names import *
from store import *
from game import *
from main import *
def submitnames():
name1 = name1entry.get()
name2 = name2entry.get()
name3 = name3entry.get()
name4 = name4entry.get()
name5 = name5entry.get()
# Full Error Report
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 1550, in __call__
return self.func(*args)
File ***************/main.py", line 33, in playbuttoncommands
names()
NameError: name 'names' is not defined
The problem is that you have a circular import, because main.py imports names.py, which then imports main.py. You should avoid these, as they cause problems like you are seeing. (The error report doesn't show all those layers, did you leave some out?)
Organize your code so that if moduleA imports moduleB, then moduleB doesn't need to import moduleA.
BTW: "from xyz import *" is discouraged, because it makes it hard to see where names were defined.
In this app I'm trying to execute a popup in which an user can write a date. This popup has to occur after the user clicks a submit button I have already created. The date the user input into this popup has to be saved into a variable which will be used later on on the code. In order to do all this I tried the following:
def CreateOrderPop(self):
def popup():
#contenido = input("Contenido de Orden ")
#diaDeEntregar = input("Dia de Entrega")
self.userentryA = Entry("Dia de Entrega: ")
self.userentryA.pack()
self.userentryAbu = Button(text= "Guardar", command = self.guardarFechaOrden)
self.userentryAbu.pack()
def guardarFechaOrden(self):
global userDate
userDate = self.userentryA.get()
self.destroy()
def submit(self):
result = next(self.counter)
global orderResult
orderResult = str(result)
global contents1
contents1 = ("Nombre: {}".format(self.entry_name.get()))
global contents2
contents2 = ("Email: {}".format(self.entry_email.get()))
global contents3
contents3 = ("Num Cel/Tel: {}".format(self.entry_numtc.get()))
global contents4
contents4 = ("InformaciĆ³n Adicional: {}".format(self.entry_addinf.get(1.0, "end")))
def CreateOrder():
fecha = datetime.now()
fechaDeCreacion = fecha.strftime(" %A, %B %d, %Y" )
#diaDeEntregar = userDate
#global fechaDeEntrega
#fechaDeEntrega = fechaDeCreacion + str(diaDeEntregar)
numOrden = orderResult
return fechaDeCreacion, orderResult
completeOrden = [contents1, contents2, contents3, contents4, CreateOrder()]
completeOrdenEnum = "Orden Num:" + orderResult, completeOrden
Database.mainDatabase.append(completeOrdenEnum)
command = self.CreateOrderPop()
After running the code and clicking the submit button, everything runs normal except I don't get the popup I want.
CHANGES
I added this class to help me create what I was looking for:
class PopOrden:
def __init__(self,master):
self.master = master
top=self.top=Toplevel(master)
self.l=Label(top,text="Fecha de Entrega")
self.l.pack()
self.e=Entry(top)
self.e.pack()
self.b=Button(top,text='Ok',command=self.cleanup)
self.b.pack()
def cleanup(self):
self.value=self.e.get()
self.top.destroy()
def entryValue(self):
return self.w.value
print(self.w.value)
The previous code along with this edited code:
def submit(self):
result = next(self.counter)
print (result)
def controLoo():
if result == 1:
self.CreateOrderPop()
command = controLoo()
global orderResult
orderResult = str(result)
global contents1
contents1 = ("Nombre: {}".format(self.entry_name.get()))
global contents2
contents2 = ("Email: {}".format(self.entry_email.get()))
global contents3
contents3 = ("Num Cel/Tel: {}".format(self.entry_numtc.get()))
global contents4
contents4 = ("InformaciĆ³n Adicional: {}".format(self.entry_addinf.get(1.0, "end")))
def CreateOrder():
fecha = datetime.now()
fechaDeCreacion = fecha.strftime(" %A, %B %d, %Y" )
#diaDeEntregar = PopOrden
#global fechaDeEntrega
#fechaDeEntrega = fechaDeCreacion + str(diaDeEntregar)
numOrden = orderResult
return fechaDeCreacion, orderResult
completeOrden = [contents1, contents2, contents3, contents4, CreateOrder()]
completeOrdenEnum = "Orden Num:" + orderResult, completeOrden
Database.mainDatabase.append(completeOrdenEnum)
command = self.database_window()
self.clear()
messagebox.showinfo(title = "Orden #"+ orderResult, message = "Orden Guardada")
However, I'm NOW having issues with a blank tk popu that's also generated with the popup I want.
I am not sure what you mean by everything runs normal, because your code seems to have some major formatting issues (indentation to say the least). However, 'pop-ups' are usually achieved with Toplevel() widgets. See this useful resource. It is a great resource for all things tkinter in my opinion.
Also, you might find the answer to this question helpful.
Why dont you use a message box directly
from tkinter import *
import tkMessageBox
root = Tk()
def popUp():
result = tkinter.messageBox.popUp("Quiz","Are you ready? ")
# result wil be yes or no
if result == 'yes':
#do something
else:
# do something
submitButton = Button(root,text= "Submit")
submitButton.bind("<Button-1",popup)
# onleft click on submit popup method gets called
submitButton.pack()
I have the same problem mentioned here : Not being able to edit NSTextField on NSPopover even though Editable behavior is set. The solution seems to be to override the canBecomeKeyWindow of NSWindow. I am trying to do the same thing in PyObjC, but I am getting an error Python signature doesn't match implied objective-C signature.
In the following code, if I comment out canBecomeKeyWindow_(), then the app runs as expected, but I am not able to click and edit the textfields.
# from Cocoa import *
from AppKit import NSWindowController, NSApplication, NSApp, NSMaxYEdge, NSImage, NSStatusBar, NSMenu, NSMenuItem, NSVariableStatusItemLength, NSRect
from Cocoa import objc
from Foundation import NSUserNotification, NSUserNotificationCenter, NSObject
from PyObjCTools import AppHelper
import webbrowser
import subprocess
import os
global popover
class TestApp(NSApplication):
def finishLaunching(self):
# Make statusbar item
statusbar = NSStatusBar.systemStatusBar()
self.statusitem = statusbar.statusItemWithLength_(NSVariableStatusItemLength)
self.icon = NSImage.alloc().initByReferencingFile_('app-icon.png')
self.icon.setScalesWhenResized_(True)
self.icon.setSize_((20, 20))
self.statusitem.setImage_(self.icon)
self.statusitem.setHighlightMode_(1)
# make the menu
self.menubarMenu = NSMenu.alloc().init()
self.menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Login', 'loginCallback:', '')
self.menubarMenu.addItem_(self.menuItem)
self.quit = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '')
self.menubarMenu.addItem_(self.quit)
# add menu to statusitem
self.statusitem.setMenu_(self.menubarMenu)
def loginCallback_(self, notification):
# Initiate the contrller with a XIB
viewController = SimpleXibDemoController.alloc().initWithWindowNibName_("Login")
# Show the window
viewController.showWindow_(viewController)
rect = self.statusitem.valueForKey_('button').frame()
viewController.popover.showRelativeToRect_ofView_preferredEdge_(rect, self.statusitem.valueForKey_('button'), NSMaxYEdge)
class SimpleXibDemoController(NSWindowController):
popover = objc.IBOutlet()
counterTextField = objc.IBOutlet()
username_field = objc.IBOutlet()
password_field = objc.IBOutlet()
submit_button = objc.IBOutlet()
def canBecomeKeyWindow_(self):
return 1
def windowDidLoad(self):
NSWindowController.windowDidLoad(self)
#objc.IBAction
def submit_(self, sender):
username = self.username_field.stringValue()
password = self.password_field.stringValue()
self.updateDisplay(username + ' ' + password)
def updateDisplay(self, value):
self.counterTextField.setStringValue_(value)
if __name__ == "__main__":
app = TestApp.sharedApplication()
icon = NSImage.alloc().initByReferencingFile_('app-icon.png')
app.setApplicationIconImage_(icon)
AppHelper.runEventLoop()
It looks like you're adding an underscore where you shouldn't. The PyObjC bridge will translate it into a colon. Besides that, the corresponding Python boolean value should be True. Thus, the correct function would look like this:
def canBecomeKeyWindow(self):
return True
I have modified the pywin package demo that creates a button to excel ribbon bar. Once the button is pressed the selected text is run in command line and the selected text is replaced by output.
There is a problem with registering the program with different clsid-filename combination. I cannot change the clsid and/or the filename of the code. If I create a copy of this file, modify and register it, The COM-object that is run is the original excelAddin.py not my new modified file. I am now missing a step in the COM registration process. What line should I add and where?
from win32com import universal
from win32com.server.exception import COMException
from win32com.client import gencache, DispatchWithEvents
import winerror
import pythoncom
from win32com.client import constants, Dispatch
import sys
import win32traceutil
# Support for COM objects we use.
gencache.EnsureModule('{00020813-0000-0000-C000-000000000046}', 0, 1, 3, bForDemand=True) # Excel 9
gencache.EnsureModule('{2DF8D04C-5BFA-101B-BDE5-00AA0044DE52}', 0, 2, 1, bForDemand=True) # Office 9
# The TLB defiining the interfaces we implement
universal.RegisterInterfaces('{AC0714F2-3D04-11D1-AE7D-00A0C90F26F4}', 0, 1, 0, ["_IDTExtensibility2"])
class ButtonEvent:
def OnClick(self, button, cancel):
import win32ui # Possible, but not necessary, to use a Pythonwin GUI
import win32con
import subprocess
app = Dispatch("Word.Application")
cmd = app.Selection
#subprocess.Popen(str(cmd))
cmdP = subprocess.Popen(str(cmd), shell = True, stdout = subprocess.PIPE)
txt = cmdP.stdout.readlines()
output = ''
for line in txt:
output += line
app.Selection.TypeText(output)
#win32ui.MessageBox(txt, "Python Test",win32con.MB_OKCANCEL)
return cancel
class ExcelAddin:
_com_interfaces_ = ['_IDTExtensibility2']
_public_methods_ = []
_reg_clsctx_ = pythoncom.CLSCTX_INPROC_SERVER
#_reg_clsid_ = ""
_reg_clsid_ = "{C5482ECA-F559-45A0-B078-B2036E6F011A}"
#_reg_clsid_ = "{E44EF798-7FDF-4015-AED6-00234CBBBA77}"
#_reg_clsid_ = "{91A89B71-56C0-4a76-BF1F-CF52E3671740}"
_reg_progid_ = 'Juha.test'#"Python.Test.ExcelAddin2"
_reg_policy_spec_ = "win32com.server.policy.EventHandlerPolicy"
def __init__(self):
self.appHostApp = None
def OnConnection(self, application, connectMode, addin, custom):
print "OnConnection", application, connectMode, addin, custom
try:
self.appHostApp = application
cbcMyBar = self.appHostApp.CommandBars.Add(Name="PythonBar",
Position=constants.msoBarTop,
MenuBar=constants.msoBarTypeNormal,
Temporary=True)
btnMyButton = cbcMyBar.Controls.Add(Type=constants.msoControlButton, Parameter="Greetings")
btnMyButton=self.toolbarButton = DispatchWithEvents(btnMyButton, ButtonEvent)
btnMyButton.Style = constants.msoButtonCaption
btnMyButton.BeginGroup = True
btnMyButton.Caption = "&Run..."
btnMyButton.TooltipText = "Runs the selected text in command line"
btnMyButton.Width = "34"
cbcMyBar.Visible = True
except pythoncom.com_error, (hr, msg, exc, arg):
print "The Excel call failed with code %d: %s" % (hr, msg)
if exc is None:
print "There is no extended error information"
else:
wcode, source, text, helpFile, helpId, scode = exc
print "The source of the error is", source
print "The error message is", text
print "More info can be found in %s (id=%d)" % (helpFile, helpId)
def OnDisconnection(self, mode, custom):
print "OnDisconnection"
self.appHostApp.CommandBars("PythonBar").Delete
self.appHostApp=None
def OnAddInsUpdate(self, custom):
print "OnAddInsUpdate", custom
def OnStartupComplete(self, custom):
print "OnStartupComplete", custom
def OnBeginShutdown(self, custom):
print "OnBeginShutdown", custom
def RegisterAddin(klass):
import _winreg
key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Office\\Word\\Addins")
#key = _winreg.CreateKey(_winreg.HKEY_LOCAL_MACHINE, "Software\\Classes\\CLSID")
subkey = _winreg.CreateKey(key, klass._reg_progid_)
_winreg.SetValueEx(subkey, "CommandLineSafe", 0, _winreg.REG_DWORD, 0)
_winreg.SetValueEx(subkey, "LoadBehavior", 0, _winreg.REG_DWORD, 3)
_winreg.SetValueEx(subkey, "Description", 0, _winreg.REG_SZ, "Runs selection in command line and pastes output")
_winreg.SetValueEx(subkey, "FriendlyName", 0, _winreg.REG_SZ, "cmdlineRunner")
def UnregisterAddin(klass):
import _winreg
try:
_winreg.DeleteKey(_winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Office\\Word\\Addins\\" + klass._reg_progid_)
except WindowsError:
pass
if __name__ == '__main__':
import win32com.server.register
win32com.server.register.UseCommandLine(ExcelAddin)
if "--unregister" in sys.argv:
UnregisterAddin(ExcelAddin)
else:
RegisterAddin(ExcelAddin)
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