【问题标题】:Python 3 Tkinter - How to call a function from another classPython 3 Tkinter - 如何从另一个类调用函数
【发布时间】:2017-06-10 22:25:57
【问题描述】:

我试图让我的保存按钮调用另一个类的函数。我想尽可能多地点击保存按钮,它应该每次都打印“hello people”。不过,我无法让保存按钮正常工作。

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

【问题讨论】:

标签: python-2.7 python-3.x tkinter


【解决方案1】:

在您的documentMaker 类中,将test 方法更改为@staticmethod

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

那么你saveButton的命令可以是:

command = documentMaker.test

staticmethod 绑定到类,而不是像实例方法那样绑定到类的实例。所以,我们可以直接从类名中调用它。如果您不希望它成为staticmethod,您可以将其保留为实例方法并将命令行更改为:

command = documentMaker().test

【讨论】:

    猜你喜欢
    • 2016-02-21
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 2013-03-13
    • 2017-01-28
    • 2015-08-06
    • 1970-01-01
    • 2020-04-16
    相关资源
    最近更新 更多