Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
455 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...