how to call a function from another script inside an imported class

299 Views Asked by At

I am building my first larger Python application using tkinter, python 3.6.3 and window OS. The GUI for the application consists of a Notebook with several tabs. Each of the tabs in turn contains a Labelframe which in turn contains a number of other widgets.

When searching Stackflow, I found the idea to lets each labelFrame be a class. Thereafter import the class in the main.py and finally creating an instance of the class.

Now when pressing the button 'Start' in tab1 I would like to execute the 'printThis' function. Ideally I would like to use the function defined in the script main.py. It would also be interested in knowing how to call the 'printThis' method withing the Run_Test_Window class. Unfortunately I have not solved either problem.

Interestingly the program actually prints "Now successful" without that I do anything but when I press the 'Start'-button nothing happens.

Grateful for help! Thanks!

main.py

import tkinter as tk  
import tkinter.ttk as ttk

import RunTestClass as RT

def printThis():
  print('Successful')

root    = tk.Tk()
note    = ttk.Notebook(root)
note.grid()  

tab1    = ttk.Label(note, width = -20)
note.add(tab1, text = "       Run Test      ")

window1 = RT.Run_Test_Window(tab1)

root.mainloop()

RunTestClass.py

import tkinter as tk
import tkinter.ttk as ttk

# from main import printThis

class Run_Test_Window:

    def printThis(self):
        print('Now successful!') 

    def __init__(self,tab1):
        runTestLabelFrame = ttk.LabelFrame(text ="Run Test", padding =10)
        runTestLabelFrame.grid(in_ = tab1, padx = 20, pady = 20)

        self.startButton  = ttk.Button(runTestLabelFrame,    text="START",command=self.printThis())
        self.startButton.grid(row=5, column=1, padx = 10)
1

There are 1 best solutions below

2
ViG On

If I'm correct you want the button to use the printThis() from main. This can be done by adding the following in your main:

rt = RT.Run_Test_Window(tab1)
rt.startButton.configure(command=printThis)

To call the printThis() defined in RunTestClass, use (also in main)

rt.printThis()

Note: leave the brackets when creating the button in the command argument. So change it to this:

self.startButton  = ttk.Button(runTestLabelFrame,    text="START",command=self.printThis)