2017-06-10 57 views
-1

我想让我的保存按钮调用另一个类的函数。我想单击保存按钮尽可能多,它应该每次打印“你好人”。尽管如此,我无法使保存按钮正常工作。Python 3 Tkinter - 如何从另一个类调用函数

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() 
+1

看到这个问题我回答了一段时间后https://stackoverflow.com/questions/ 44012740 /如何将所选文件名从tkfiledialog-gui转换为另一个功能 –

+0

尝试[google](https://www.google.com/search?q=how+to+调用+ A +功能+从+另一个+类和OQ =如何+呼叫+ A +功能+从+ A&AQS = chrome.1.69i57j0l5.10235j0j4&的SourceID =铬&即= UTF-8#newwindow = 1&q =蟒+如何+呼叫+另一个+类+ + + +函数+)你的标题。有许多结果回答了这个问题。这种问题很容易在google和stackoverflow上找到答案。 –

+0

[从另一个类调用类方法]的可能重复(https://stackoverflow.com/questions/3856413/call-class-method-from-another-class) –

回答

0

在你documentMaker类中,test方法改变为@staticmethod

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

那么您saveButton的命令可以是:

command = documentMaker.test 

staticmethod结合到类,而不是类实例方法的类实例。所以,我们可以直接从课程名称中调用它。如果你不希望它是一个staticmethod,你可以保持它的一个实例方法,并有命令行更改为:

command = documentMaker().test 
相关问题