在子 class python 中调用父方法
Calling parent method inside child class python
这是我的代码:
class GUI(playGame):
def __init__(self):
import tkinter as tk
home=tk.Tk()
home.title("Tic Tac Toe")
home.geometry("160x180")
w,h=6,3
self.c1r1=tk.Button(text='',width=w, height=h, command=lambda: userTurn(self.c1r1))
self.c1r1.grid(column=1,row=1)
home.mainloop()
因此,userTurn 已在父级 class playGame 中定义,但是当我 运行 并单击按钮 c1r1 时,我得到
NameError:名称 'userTurn' 未定义
您需要在函数调用中添加一个self
。您可能应该在初始化中调用 super()
:
import tkinter as tk
class playGame():
def userTurn(self,foo):
pass
class GUI(playGame):
def __init__(self):
super().__init__()
home=tk.Tk()
home.title("Tic Tac Toe")
home.geometry("160x180")
w,h=6,3
self.c1r1=tk.Button(text='',width=w, height=h, command=lambda: self.userTurn(self.c1r1))
self.c1r1.grid(column=1,row=1)
home.mainloop()
这是我的代码:
class GUI(playGame):
def __init__(self):
import tkinter as tk
home=tk.Tk()
home.title("Tic Tac Toe")
home.geometry("160x180")
w,h=6,3
self.c1r1=tk.Button(text='',width=w, height=h, command=lambda: userTurn(self.c1r1))
self.c1r1.grid(column=1,row=1)
home.mainloop()
因此,userTurn 已在父级 class playGame 中定义,但是当我 运行 并单击按钮 c1r1 时,我得到 NameError:名称 'userTurn' 未定义
您需要在函数调用中添加一个self
。您可能应该在初始化中调用 super()
:
import tkinter as tk
class playGame():
def userTurn(self,foo):
pass
class GUI(playGame):
def __init__(self):
super().__init__()
home=tk.Tk()
home.title("Tic Tac Toe")
home.geometry("160x180")
w,h=6,3
self.c1r1=tk.Button(text='',width=w, height=h, command=lambda: self.userTurn(self.c1r1))
self.c1r1.grid(column=1,row=1)
home.mainloop()