Shammir
Shammir

Reputation: 979

Python Tkinter- method for printing not working after being called from another script

I have a class called app.py within that class there's a method called print_raw_records_screen here's the part of the class and the method

app.py


#!/usr/bin/python
# -*- coding: utf-8 -*-


from Tkinter import *
from ttk import *
import os
import mftsession


class Example(Frame):

def __init__(self, parent):
    Frame.__init__(self, parent)   
     
    self.parent = parent
    self.filename = ""        
    self.initUI()

#defining a function that that receives the raw records from the mftsession.py and print it to the screen
#this script will be called by the mftsession.py in 
#process_mftfile()
def print_raw_records_screen(self,records):
    self.area.delete(1.0, "end")
    self.area.insert('1.0',records)
    
    
def initUI(self):
  
    self.parent.title("Mtf Analyzer")
    
    #initializing and configuring menubar

    menubar = Menu(self.parent)
    self.parent.config(menu=menubar)
    
    fileMenu = Menu(menubar)
    fileMenu.add_command(label="Open file", command=self.fileOpen)
    fileMenu.add_command(label="Exit", command=self.onExit)
    menubar.add_cascade(label="File", menu=fileMenu)


    #specify grid row and column spaces
   
    self.pack(fill=BOTH, expand=True)

    self.columnconfigure(1, weight=1)
    self.columnconfigure(3, pad=7)
    self.rowconfigure(3, weight=1)
    self.rowconfigure(5, pad=7)
    
    lbl = Label(self, text="File Name")
    lbl.grid(row=1, column=0, sticky=W, pady=4, padx=5)

    self.filename_area = Entry(self)
    self.filename_area.grid(row=1, column=1, columnspan=5, padx=5, sticky=E+W+S+N)

    analize_button = Button(self, text="Analize",  command=self.processFile)
    analize_button.grid(row=1, column=6, padx=5)
    
    self.area = Text(self)
    self.area.grid(row=2, column=1, columnspan=2, rowspan=4, 
        padx=5, sticky=E+W+S+N)



    #configure the raw output view
    

def onExit(self):
    self.quit()

#this function selects and opens the file to analize
def fileOpen(self):
    from tkFileDialog import askopenfilename

    Tk().withdraw() 
    self.filename = askopenfilename() 

    #populate the filename field
    self.set( self.filename)
   


#do the processing of the file obtained. Populate the file NAME entry or
#send the filename to the analyzeMFT.py
def processFile(self):       
    arguments = "analyzeMFT.py -f "+self.filename+" -d --bodyfull -l -o "+self.filename+".csv"
    os.system(arguments)

    mftsession.MftSession.process_mft_file(self)

#get and set methods for the entry field
def get(self):
    return self.filename_area.get()

def set(self, value):
    self.filename_area.delete(0, END)
    self.filename_area.insert(0,value)



def main():

  root = Tk()
  root.geometry("450x350+500+500")
  app = Example(root)
  root.mainloop()  


if __name__ == '__main__':
    main()

This method is called by another external script like this

mftsession.py


import csv
import json
import os
import sys
from optparse import OptionParser

import mft

 import app
from Tkinter import *
from ttk import *

class MftSession:
"""Class to describe an entire MFT processing session"""

@staticmethod
def fmt_excel(date_str):
    return '="{}"'.format(date_str)

@staticmethod
def fmt_norm(date_str):
    return date_str


def __init__(self):       

    self.mft = {}
    self.fullmft = {}
    self.folders = {}
    self.debug = False
    self.mftsize = 0

def process_mft_file(self):        

    root = Tk()
    appi = app.Example(root)

    self.sizecheck()

    self.build_filepaths()

    # reset the file reading
    self.num_records = 0
    self.file_mft.seek(0)
    raw_record = self.file_mft.read(1024)

    if self.options.output is not None:
        self.file_csv.writerow(mft.mft_to_csv(None, True, self.options))

    while raw_record != "":
        record = mft.parse_record(raw_record, self.options)
        if self.options.debug:
            print record
            appi.print_raw_records_screen(raw_record )  #THIS FUNCTION WHILE INVOKED THIS WAY IS NOT WORKING
            ..........

The script analyzeMFT.py called by the app.py through the subrouting

#!/usr/bin/python
import sys
from os import path

def main(): 


  session = mftsession.MftSession()
  session.mft_options()
  session.open_files()
  session.process_mft_file()



 if __name__ == '__main__':

   if __package__ is None:
        sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
    import mftsession
    main()
    
else:
    import mftsession
    main()     

When called this way it prints nothing to the window, but when i invoke it for testing within its own class it prints the test

def print_raw_records_screen(self,records):
    self.area.delete(1.0, "end")
    self.area.insert('1.0', records)

and invoke like print_raw_records_screen("any test"): in the app.py

enter image description here

An image can tell alot. and summarize

What am i doing wrong? I sense it's the instantiation am doing wrong. I need diretions please

enter image description here

enter image description here

Upvotes: 0

Views: 589

Answers (1)

Mike - SMT
Mike - SMT

Reputation: 15226

From what I can see here you have a few issues causing problems.

  1. you are importing app.py on mftsession.py instead importing mftsession.py on app.py.

  2. You are trying to use appi.print_raw_records_screen(raw_record) on a completely different instance of the Example() class with appi = app.Example(root) remove that part all together.

  3. It is bad practice to importing inside a function. Import at the start of each py file.

There is so many things going on in your code I had to create a Minimal, Complete, and Verifiable example example of my own to illustrate the relation between files.

Here is a simple example of how the 2 files can interact and the way I think you are trying to do things.

Here I have created a main file called app.py:

from Tkinter import *
# You might need to import the py file with the package name as well.
# Change the package name to the package your python files are located in.
import PACKAGE_NAME.file_b

class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent
        self.filename = ""        
        analize_button = Button(self.parent, text="Analize",  command=self.processFile)
        analize_button.pack()
        self.area = Text(self.parent, height = 2, width = 40)
        self.area.pack()

    def print_raw_records_screen(self,records):
        self.area.delete(1.0, "end")
        self.area.insert('1.0',records)

    def processFile(self):       
        PACKAGE_NAME.file_b.process_mft_file(self)



if __name__ == "__main__":
    root = Tk()
    app = Example(root)
    root.mainloop()

Here I have created a file called file_b.py

from Tkinter import *

def process_mft_file(self):        
    record = "Some values assigned to a variable"
    self.print_raw_records_screen(record)

The results look something like this:

enter image description here

Upvotes: 1

Related Questions