如何在python中从类调用方法

2024-03-28 17:01:00 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中,如何从类Acceptor调用方法bio_info?你知道吗

import sys
import Tkinter
from Tkinter import *
from tkMessageBox import *
from tkSimpleDialog import *


class Acceptor():

    def bio_info(self):

    #this method takes in input from the keyboard console

        def__init__(self,name,mat_no,semester)
        self.name=name
        self.mat_no=mat_no
        self.semester=semester


        Label(top,text='Name').grid(row=0)
        Label(top,text='Matric No').grid(row=1)
        Label(top,text='Semester').grid(row=2)

        name=Entry(top)
        mat_no=Entry(top)
        semester=Entry(top)


        name.grid(row=0,column=1)
        mat_no.grid(row=1,column=1)
        semester.grid(row=2,column=1)

        return name
        return mat_no
        return semester    


main = Tk()

#This defines the size of the main window
main.geometry('640x480')

    #This takes care of the configuration of the main window, buttons and labels inclusive
main.title('Result Calculator App')
mainLabel=Tkinter.Label(main,text='Result Calculator',bd=10, relief=RIDGE,fg='cyan')
mainLabel.pack(fill=BOTH)
mainLabel.config(font=('algerian',35, 'bold'), bg='blue',fg='orange')
calculate=Button(text="CALCULATE",font=('joan',20,'bold'),bg='black',fg='green',width=15,cursor='hand2',relief=SOLID,
command=Acceptor.bio_info)
calculate.pack()


print'This program ran correctly'
main.mainloop()

Tags: thenotextnamefromimportselfmain
3条回答

调用它就像调用python中任何其他类中的任何其他方法一样。创建类的实例,然后调用实例上的方法:

acceptor = Acceptor()
...
calculate=Button(..., command=acceptor.bio_info, ...)

正如teckydesigner所说,在使用类之前,需要创建类的实例。 你的代码command = Acceptor.bio_info无法编译,因为bio\u info是一个方法,需要像这样调用:myAcceptor.bio_info()。你知道吗

您需要创建一个类的实例并从该实例调用方法。示例:

myAcceptor = Acceptor()
myAcceptor.bio_info()

相关问题 更多 >