Python Tkinter-从另一个脚本调用后无法打印的方法 [英] Python Tkinter- method for printing not working after being called from another script

查看:59
本文介绍了Python Tkinter-从另一个脚本调用后无法打印的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在您说这是重复或否决之前,请通读一遍.我在该类中有一个名为 app.py 的类,有一个名为 print_raw_records_screen 的方法,这是该类的一部分和方法

app.py#!/usr/bin/python# -*- 编码:utf-8 -*-从 Tkinter 导入 *从 ttk 导入 *导入操作系统导入 mftsession类示例(框架):def __init__(self, parent):Frame.__init__(self, parent)self.parent = 父母self.filename = ""self.initUI()#定义一个从 mftsession.py 接收原始记录并将其打印到屏幕的函数#这个脚本会被mftsession.py中的调用#process_mftfile()def print_raw_records_screen(self,records):self.area.delete(1.0, "end")self.area.insert('1.0',records)定义 initUI(self):self.parent.title("Mtf 分析器")#初始化和配置菜单栏菜单栏 = 菜单(self.parent)self.parent.config(菜单=菜单栏)文件菜单 = 菜单(菜单栏)fileMenu.add_command(label="打开文件", command=self.fileOpen)fileMenu.add_command(label="Exit", command=self.onExit)menubar.add_cascade(标签=文件",菜单=文件菜单)#指定网格行和列空间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="文件名")lbl.grid(row=1, column=0,sticky=W, pady=4, padx=5)self.filename_area = 条目(自我)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 = 文本(自我)self.area.grid(row=2, column=1, columnspan=2, rowspan=4,padx=5,粘性=E+W+S+N)#配置原始输出视图def onExit(self):self.quit()#该函数选择并打开要分析的文件def fileOpen(self):从 tkFileDialog 导入 askopenfilenameTk().withdraw()self.filename = askopenfilename()#填充文件名字段self.set(self.filename)#对获取的文件进行处理.填充文件 NAME 条目或#将文件名发送到analyzeMFT.pydef processFile(self):争论 = "analyzeMFT.py -f "+self.filename+" -d --bodyfull -l -o "+self.filename+".csv"os.system( 争论 )mftsession.MftSession.process_mft_file(self)#get 和 set 输入字段的方法定义获取(自我):返回 self.filename_area.get()定义集(自我,价值):self.filename_area.delete(0, END)self.filename_area.insert(0,value)定义主():根 = Tk()root.geometry("450x350+500+500")app = 示例(根)root.mainloop()如果 __name__ == '__main__':主要的()

这个方法被另一个这样的外部脚本调用

mftsession.py导入 csv导入json导入操作系统导入系统从 optparse 导入 OptionParser进口制造商导入应用从 Tkinter 导入 *从 ttk 导入 *MftSession 类:"""描述整个 MFT 处理会话的类"""@静态方法def fmt_excel(date_str):返回 '​​="{}"'.format(date_str)@静态方法def fmt_norm(date_str):返回日期字符串def __init__(self):self.mft = {}self.fullmft = {}self.folders = {}self.debug = Falseself.mftsize = 0def process_mft_file(self):根 = Tk()appi = app.Example(root)self.sizecheck()self.build_filepaths()# 重置文件读取self.num_records = 0self.file_mft.seek(0)raw_record = self.file_mft.read(1024)如果 self.options.output 不是 None:self.file_csv.writerow(mft.mft_to_csv(None, True, self.options))而 raw_record != "":record = mft.parse_record(raw_record, self.options)如果 self.options.debug:打印记录appi.print_raw_records_screen(raw_record) #此功能在以这种方式调用时不起作用.....

app.py通过子路由调用的脚本analyzeMFT.py

#!/usr/bin/python导入系统从操作系统导入路径定义主():session = mftsession.MftSession()session.mft_options()session.open_files()session.process_mft_file()如果 __name__ == '__main__':如果 __package__ 是 None:sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))导入 mftsession主要的()别的:导入 mftsession主要的()

当以这种方式调用时,它不会向窗口打印任何内容,但是当我在它自己的类中调用它进行测试时,它会打印测试

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

并在 app.py 中像 print_raw_records_screen("any test"): 一样调用

一张图片可以说明很多.并总结

我做错了什么?我感觉这是实例化做错了.我需要方向请

解决方案

从我在这里看到的情况来看,您有一些问题导致了问题.

  1. 您在 mftsession.py 上导入 app.py 而不是在 app.py<上导入 mftsession.py/code>.

  2. 您正在尝试在 Example() 类的一个完全不同的实例上使用 appi.print_raw_records_screen(raw_record)appi = app.Example(root) 一起删除那部分.

  3. 在函数内部导入是不好的做法.在每个 py 文件的开头导入.

您的代码中发生了很多事情,我不得不创建一个

Before you say this is a duplicate or downvote, please read through. 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):       
    arguements = "analyzeMFT.py -f "+self.filename+" -d --bodyfull -l -o "+self.filename+".csv"
    os.system( arguements )

    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

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

解决方案

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:

这篇关于Python Tkinter-从另一个脚本调用后无法打印的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆