如何在另一个文件中执行类函数?

时间:2017-02-11 17:10:41

标签: python class tkinter

我正在尝试调用一个类函数,它会将一些文本写入Tkinter的控制台窗口。

然而,当我尝试运行它时。我收到以下错误。

TypeError: write() missing 1 required positional argument: 'txt'

这是我的完整代码:

main.py

from tkinter import *
from tkinter.filedialog import askdirectory
import os
import nam


class Window(Frame):

    def __init__(self, master = None):
        Frame.__init__(self, master)
        self.master = master
        self.init_window()


    def init_window(self):
        self.master.title("Source Data Checker")
        self.pack(fill=BOTH, expand=1)

        self.pathLabel = Label(text='Select the location of the source data below and press "Generate Excel"')
        self.pathLabel.place(x=110, y=40)

        self.selectFolderButton = Button(self, text='Select Folder', command=self.openfile)
        self.selectFolderButton.place(x=180, y=350)

        self.executeButton= Button(self, text='Generate Excel', command=self.run)
        self.executeButton.config(state=DISABLED)
        self.executeButton.place(x=330, y=350)

        self.outputWindow = Text()
        self.outputWindow.place(x=100, y=80)
        self.outputWindow.config(width=50, height=15)

    def openfile(self): #open the file
        self.directory = askdirectory()
        if self.directory != '':
            nam.panels_count(self.directory)
            self.executeButton.config(state=NORMAL)
            print(nam.a_nam)

    def run(self, txt):
        pass

    def write(self, txt):
        self.outputWindow.insert(END, str(txt))
        self.update_idletasks()

if __name__ == '__main__':
    root = Tk()
    root.geometry("600x400")
    app = Window(root)
    root.mainloop()

nam.py

from main import *

def panels_count(folder):

    Window.write('test')

我在想我可能需要实例化它。但是当我这样做时,程序甚至都不会运行。

我错过了什么?

1 个答案:

答案 0 :(得分:6)

您需要在实例上调用方法 。你在课堂上调用它,此时self没有任何内容可以约束,所以Window.write('test')期望两个参数但是没有值txt

openfile方法可以通过self访问该实例;将其传递给另一个函数:

def openfile(self): #open the file
    self.directory = askdirectory()
    if self.directory != '':
        nam.panels_count(self, self.directory)
        self.executeButton.config(state=NORMAL)
        print(nam.a_nam)

def panels_count(app, folder):
    app.write('test')