-1

I am trying to get my save button to call a function from another class. I would like to click on the save button as much as I want and it should print "hello people" every time. Though, I am having trouble in getting the save button to work.

import tkinter as tk
from tkinter import filedialog


class Application(tk.Frame): 
    def __init__(self, parent):
        tk.Frame.__init__(self, parent) 
        self.parent = parent
        self.pack() 
        self.createWidgets()

    def createWidgets(self):

        #save button
        self.saveLabel = tk.Label(self.parent, text="Save File", padx=10, pady=10)
        self.saveLabel.pack()
        #When I click the button save, I would like it to call the test function in the documentMaker class
        self.saveButton = tk.Button(self.parent, text = "Save", command = documentMaker.test(self))
        self.saveButton.pack()


class documentMaker():
    def test(self):

      print ("hello people")  

root = tk.Tk()
app = Application(root) 
app.master.title('Sample application')
object = documentMaker()
object.test()

app.mainloop()
B Hok
  • 145
  • 1
  • 6
  • 15
  • 1
    See this question I answered a while back https://stackoverflow.com/questions/44012740/how-to-pass-the-selected-filename-from-tkfiledialog-gui-to-another-function – Pax Vobiscum Jun 10 '17 at 22:28
  • Try to [google](https://www.google.com/search?q=how+to+call+a+function+from+another+class&oq=how+to+call+a+function+from+a&aqs=chrome.1.69i57j0l5.10235j0j4&sourceid=chrome&ie=UTF-8#newwindow=1&q=python+how+to+call+a+function+from+another+class) your title. There many results that answer just this question. This kind of question is very easy to find an answer on google and stackoverflow. – Mike - SMT Jun 10 '17 at 22:42
  • Possible duplicate of [Call Class Method From Another Class](https://stackoverflow.com/questions/3856413/call-class-method-from-another-class) – Mike - SMT Jun 10 '17 at 22:44

1 Answers1

2

In your documentMaker class, change the test method to a @staticmethod:

class documentMaker():
    @staticmethod
    def test(cls):   
      print ("hello people") 

Then your saveButton's command can be:

command = documentMaker.test

A staticmethod is bound to the class, not to an instance of the class like an instance method. So, we can call it from the class's name directly. If you did not want it to be a staticmethod, you could keep it an instance method and have the command line change to:

command = documentMaker().test
rassar
  • 5,412
  • 3
  • 25
  • 41