Keva161
Keva161

Reputation: 2693

How do I execute a class function in another file?

I'm trying to call a class function that will write some text to a console window in Tkinter.

However when I try to run it. I am getting the below error.

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

Here is my full code:

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')

I was thinking I may need to instantiate it. But when I do that, The program won't even run.

What am I missing?

Upvotes: 0

Views: 79

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121834

You need to call the method on an instance. You are calling it on the class, at which point there is nothing for self to be bound to, so Window.write('test') expects two arguments but doesn't have a value for txt.

The openfile method has access to the instance via self; pass that in to the other function:

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)

and

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

Upvotes: 5

Related Questions