Python 3 Tkinter - 如何从另一个类调用函数 [英] Python 3 Tkinter - How to call a function from another class
问题描述
我试图让我的保存按钮从另一个类调用函数.我想尽可能多地点击保存按钮,它应该每次都打印你好人".不过,我无法让保存按钮起作用.
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()
推荐答案
在您的 documentMaker
类中,将 test
方法更改为 @staticmethod
:
In your documentMaker
class, change the test
method to a @staticmethod
:
class documentMaker():
@staticmethod
def test(cls):
print ("hello people")
那么你的 saveButton
的命令可以是:
Then your saveButton
's command can be:
command = documentMaker.test
staticmethod
绑定到类,而不是像实例方法那样绑定到类的实例.因此,我们可以直接从类的名称中调用它.如果您不希望它成为 staticmethod
,您可以将其保留为实例方法,并将命令行更改为:
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
这篇关于Python 3 Tkinter - 如何从另一个类调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!