如何在python中从类调用方法
在下面的代码中,如何从类如何在python中从类调用方法,python,tkinter,Python,Tkinter,在下面的代码中,如何从类Acceptor调用方法bio\u 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
Acceptor
调用方法bio\u 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()
调用它就像调用python中任何其他类中的任何其他方法一样。创建该类的实例,然后对该实例调用该方法:
acceptor = Acceptor()
...
calculate=Button(..., command=acceptor.bio_info, ...)
您需要创建该类的一个实例,并从该实例调用该方法。例如:
myAcceptor = Acceptor()
myAcceptor.bio_info()
正如teckydesigner所说,在使用类之前,您需要创建类的实例。
你的代码
command=Acceptor.bio_info
不会编译,因为bio_info是一个方法,需要像这样调用:myAcceptor.bio_info()
为什么你的\uu init\uuuuu
会返回东西?你的\uu init\uuuuu
在bio_info方法中,而它应该是一个接受方法。如果要将bio_info作为类方法调用,则使用@classmethod对其进行修饰,并将self参数更改为cls,否则将构造一个Acceptor实例,将\uuuu init\uuu
中期望的值传递给它,并在实例hanks上调用bio_info以进行观察和更正。这是一个错误